簡體   English   中英

使用 if 語句遍歷列表

[英]iterating through a list with an if statement

我有一個列表,我正在使用“for”循環循環並通過 if 語句運行列表中的每個值。 我的問題是,如果列表中的所有值都通過了 if 語句,並且如果一個沒有通過,我希望它移動到列表中的下一個值,我只想讓程序執行某些操作。 當前,如果列表中的單個項目通過 if 語句,它會返回一個值。 有什么想法可以讓我指出正確的方向嗎?

Python 為您提供了大量選項來處理這種情況。 如果您有示例代碼,我們可以為您縮小范圍。

您可以查看的一個選項是all運算符:

>>> all([1,2,3,4])
True
>>> all([1,2,3,False])
False

您還可以檢查過濾列表的長度:

>>> input = [1,2,3,4]
>>> tested = [i for i in input if i > 2]
>>> len(tested) == len(input)
False

如果您使用for構造,如果遇到負面測試,您可以提前退出循環:

>>> def test(input):
...     for i in input:
...         if not i > 2:
...             return False
...         do_something_with_i(i)
...     return True

例如,上面的test function 將在第一個值為 2 或更低的值上返回 False,而僅當所有值都大於 2 時才返回 True。

也許您可以嘗試使用for... else語句。

for item in my_list:
   if not my_condition(item):
      break    # one item didn't complete the condition, get out of this loop
else:
   # here we are if all items respect the condition
   do_the_stuff(my_list)

在嘗試對數據執行任何其他操作之前,您需要遍歷整個列表並檢查條件,因此您需要兩個循環(或使用一些內置的循環來為您執行循環,如 all())。 從這個沒有什么花哨的鍵盤, http://codepad.org/pKfT4Gdc

def my_condition(v):
  return v % 2 == 0

def do_if_pass(l):
  list_okay = True
  for v in l:
    if not my_condition(v):
      list_okay = False

  if list_okay:
    print 'everything in list is okay, including',
    for v in l:
      print v,
    print
  else:
    print 'not okay'

do_if_pass([1,2,3])
do_if_pass([2,4,6])

如果您在嘗試迭代列表時從列表中刪除項目,則必須始終小心。

如果您不刪除,那么這是否有幫助:

>>> yourlist=list("abcdefg")
>>> value_position_pairs=zip(yourlist,range(len(yourlist)))
>>> value_position_pairs
[('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6)]
>>> filterfunc=lambda x:x[0] in "adg"
>>> value_position_pairs=filter(filterfunc,value_position_pairs)
>>> value_position_pairs
[('a', 0), ('d', 3), ('g', 6)]
>>> yourlist[6]
'g'

現在如果 value_position_pairs 是空的,你就完成了。 如果不是,您可以將 i 增加 1 到 go 到下一個值,或者使用數組中的 position 遍歷失敗的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM