【问题标题】:Python how to skip the first (i.e. zero) iteration using enumerate and a list?Python如何使用枚举和列表跳过第一次(即零)迭代?
【发布时间】:2015-08-18 18:14:46
【问题描述】:

我有一个表格对象。

我想检查第一行的值是否为Test,在这种情况下,我需要对表中的每一行进行处理。

否则,如果第一行没有Test 的值,我需要跳过该行并处理第 1 行及以后的内容。

因为我需要索引和行,所以我必须使用枚举,但似乎我以一种凌乱的方式使用它。在这里,我两次调用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

【问题讨论】:

  • 如果second 行的值为Test,会发生什么?如果它是第一行,它看起来会触发相同的特殊处理。无论如何,我建议跳过循环中的第一行(首先专门处理它)并使用enumerate(..., start=1) 来处理其余部分。

标签: python list enumerate


【解决方案1】:

按照凯文的建议,你可以单独处理第一项,然后继续循环:

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

【讨论】:

  • 时尚。你在这里有偏好吗,是不是更 Pythonic?我一直忘记使用iter
  • 前者让它看起来更加分离,这样可能会让你的意图更清晰。但我个人会接受这两种解决方案。
  • 另外,在你的第二个例子中,如果r == 'Test' 没有continue 语句跳过if specialHandling
  • 是的,continue 使它跳过循环体的剩余部分。您也可以在那里使用elif specialHandling,但我想明确指出,第一项的处理就在那里。我跳过了其余的,因为我假设你不想继续在第一行做“正常的事情”。
  • 是的,你是对的,我不想做“正常的事情”,但似乎,对于第一项,specialHandling 设置为True,(因为@987654331 @) 但随后 continue continues 过去 if specialHandling 声明所以我永远无法真正评估 if specialHandling
【解决方案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 循环分解到它们自己的函数中,以使其更简洁。

刚刚也注意到了 Poke 的回答 :)

【讨论】:

  • 这假定rows 是一个序列。
猜你喜欢
  • 2015-03-24
  • 2017-12-01
  • 2013-10-03
  • 2011-08-08
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多