Python 如何使用枚举和列表跳过第一次(即零次)迭代?
Python how to skip the first (i.e. zero) iteration using enumerate and a list?
我有一个 table 对象。
我想检查第一行的值是否为 Test
,在这种情况下,我需要对 table 中的每一行执行一些操作。
否则,如果第一行没有 Test
的值,我需要跳过该行并对第 1 行及以后的行执行一些操作。
因为我既需要索引又需要行,所以我不得不使用enumerate,但是我好像用的很乱。在这里,我调用了 enumerate
两次,并检查索引是否为 0
两次。有更简洁的方法吗?
for i, r in enumerate(null_clipData.rows()):
if r[0].val == 'Test':
# Do something if the first row is Test
for index, row in enumerate(null_clipData.rows()):
if index == 0:
continue # But do anything the first time (stay in this loop though)
print(index, row)
break # All through with test row
if i == 0:
continue # Don't do anything with the first row if the value was not Test
print(i, r) # Do something with i and r
按照凯文的建议,您可以单独处理第一项,然后继续循环:
rows = iter(null_clipData.rows())
firstRow = next(rows)
specialHandling = firstRow.val == 'Test'
for i, r in enumerate(rows, start=1):
if specialHandling:
# do something special with r
else:
# do the normal stuff with r
或者,您也可以将其保持在一个循环中:
specialHandling = False # default case
for i, r in enumerate(null_clipData.rows()):
if i == 0: # first item
specialHandling = r == 'Test'
continue
if specialHandling:
# do something special with r
else:
# do the normal stuff with r
rows=null_clipData.rows()
enumeration=enumerate(rows[1:])
if rows[0]=='Test':
for idx,row in enumeration:
print(idx,row)
else:
for i,r in enumeration:
print (i,r)
类似的东西?
我建议您将两个不同的 for 循环分解为它们自己的函数,以使其更清晰。
刚注意到 Poke 的回答,也是:)
我有一个 table 对象。
我想检查第一行的值是否为 Test
,在这种情况下,我需要对 table 中的每一行执行一些操作。
否则,如果第一行没有 Test
的值,我需要跳过该行并对第 1 行及以后的行执行一些操作。
因为我既需要索引又需要行,所以我不得不使用enumerate,但是我好像用的很乱。在这里,我调用了 enumerate
两次,并检查索引是否为 0
两次。有更简洁的方法吗?
for i, r in enumerate(null_clipData.rows()):
if r[0].val == 'Test':
# Do something if the first row is Test
for index, row in enumerate(null_clipData.rows()):
if index == 0:
continue # But do anything the first time (stay in this loop though)
print(index, row)
break # All through with test row
if i == 0:
continue # Don't do anything with the first row if the value was not Test
print(i, r) # Do something with i and r
按照凯文的建议,您可以单独处理第一项,然后继续循环:
rows = iter(null_clipData.rows())
firstRow = next(rows)
specialHandling = firstRow.val == 'Test'
for i, r in enumerate(rows, start=1):
if specialHandling:
# do something special with r
else:
# do the normal stuff with r
或者,您也可以将其保持在一个循环中:
specialHandling = False # default case
for i, r in enumerate(null_clipData.rows()):
if i == 0: # first item
specialHandling = r == 'Test'
continue
if specialHandling:
# do something special with r
else:
# do the normal stuff with r
rows=null_clipData.rows()
enumeration=enumerate(rows[1:])
if rows[0]=='Test':
for idx,row in enumeration:
print(idx,row)
else:
for i,r in enumeration:
print (i,r)
类似的东西? 我建议您将两个不同的 for 循环分解为它们自己的函数,以使其更清晰。
刚注意到 Poke 的回答,也是:)