[英]Python how to skip the first (i.e. zero) iteration using enumerate and a list?
我有一個桌子對象。
我想檢查第一行是否具有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
按照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
另外,您也可以將其放在一個循環中:
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的回答,那也是:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.