Python如何使用enumerate和list跳过第一次(即零)迭代?

2024-10-03 04:34:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表对象。在

我想检查第一行是否有Test的值,在这种情况下,我需要对表中的每一行执行一些操作。在

否则,如果第一行没有Test的值,我需要跳过该行,对第1行和第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

Tags: theintestforindexifwithdo
2条回答
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循环分解到它们自己的函数中,以保持它更干净。在

我也注意到了波克的回答:)

按照Kevin的建议,您可以分别处理第一项,然后继续循环:

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

或者,也可以将其保存在单个循环中:

^{pr2}$

相关问题 更多 >