2011-05-28 64 views
8

我有一個列表,我正在循環使用「for」循環,並通過if語句在列表中運行每個值。我的問題是我只想讓程序做一些事情,如果列表中的所有值都通過了if語句,並且如果沒有通過,我希望它移動到列表中的下一個值。目前,如果列表中的單個項目通過if語句,它將返回一個值。任何想法讓我指出正確的方向?使用if語句遍歷列表

+9

示例代碼總是幫助我們更好地幫助您。 – 2011-05-28 21:30:35

+3

發佈您的代碼。 – GWW 2011-05-28 21:30:45

+0

'sort'並與一個已知的src進行比較,但是正如其他人所說的那樣,發佈一些代碼以便我們可以確定您的列表的樣子! – 2011-05-28 21:34:21

回答

9

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函數將返回在這2或更低,例如第一個值false,而它會返回True只有當所有值均大於2

0

你通過你的整個列表需要循環,並檢查條件,然後再嘗試對數據做任何其他事情,所以你需要兩個循環(或者使用一些內置的循環,像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]) 
3

也許你可以嘗試用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) 
0

如果您在嘗試遍歷它時刪除列表中的項目,則必須小心。

如果你不刪除,然後這是否幫助:

>>> 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以轉到下一個值,或者使用它們在數組中的位置迭代失敗的值。