特定索引后for循环,python不起作用
所以我有一段代码,它遍历一个切换到元组的数据帧,然后遍历第一个值之后的每个值。昨天一切正常,但今天,对于某些行,它不排除第一个索引,我不知道为什么 代码如下:特定索引后for循环,python不起作用,python,loops,for-loop,Python,Loops,For Loop,所以我有一段代码,它遍历一个切换到元组的数据帧,然后遍历第一个值之后的每个值。昨天一切正常,但今天,对于某些行,它不排除第一个索引,我不知道为什么 代码如下: for rows in data.itertuples(): r = int(rows[0]) + 1 for i in rows[1:]: c = rows.index(i) print r, i, c, int(rows.index(i)), rows 我复制了前两行迭代的打印结果。第
for rows in data.itertuples():
r = int(rows[0]) + 1
for i in rows[1:]:
c = rows.index(i)
print r, i, c, int(rows.index(i)), rows
我复制了前两行迭代的打印结果。第一排工作得很好。第二排有个问题。我们所期望的是,对于它拾取行[1]的第一个元素,c将被设置为1,但实际上它是0。这是通过数据帧的行随机发生的。有人知道为什么for循环没有跳过第一个元素吗
1 3 1 1 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
1 1 3
1 27000 2 2 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
1 2 27000
1 1060 3 3 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
1 3 1060
1 QMS 4 4 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
1 4 QMS
1 ARCA 5 5 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
1 5 ARCA
1 DAY 6 6 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
1 6 DAY
1 LMT 7 7 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
1 7 LMT
**2 1 0 0 (1, 1, 3500, '1060', 'QMS', 'TEST', 'DAY', 'LMT')**
2 0 1
2 3500 2 2 (1, 1, 3500, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
2 2 3500
2 1060 3 3 (1, 1, 3500, '1060', 'QMS', 'TEST', 'DAY', 'LMT')
行。索引(i)
将在行中找到值为i
的第一项。当您到达第二个行
集合时,行[0]
等于一,因此行。索引(1)
为零,即使行[1]
也等于一
如果您只想遍历iterable的索引和值,我建议使用enumerate
for rows in data.itertuples():
r = int(rows[0]) + 1
for c, i in enumerate(rows):
#skip the first value
if c == 0:
continue
#do whatever here
或
for rows in data.itertuples():
r = int(rows[0]) + 1
for c, i in enumerate(rows[1:], 1): #skip the first item implicitly
#do whatever here