2017-04-24 84 views
0
candidates = ['abacus', 'ball', 'car'] 

for candidate in candidates: 
    if dict[candidate] == "true": 
     """next""" 
    else: 
     continue 
"""do something""" 

我在這裏要做的是檢查字典中是否存在術語,如果存在,請將控制流移到列表中的下一項候選人。我在使用next()時遇到問題。我如何去做這件事?如果條件符合,則列表中的下一項

+1

「next」是什麼意思?如果它存在,你想要發生什麼?去下一個候選人是「繼續」會做的。 –

+0

'continue'已經移動到迭代中的下一個元素,不是嗎?你想在if和else子句之間做什麼不同? –

+1

你在尋找'continue'嗎? –

回答

1

如果你想控制移動到下一個元素在列表中,如果在字典中存在的術語,你可以繼續使用。

Python中的continue語句將控件返回到while循環的開始 。 continue語句拒絕當前循環中所有剩餘的 語句,並將控件 移回到循環的頂部。

for candidate in candidates: 
    if dict.get(candidate) == "true": 
     continue 
    else: 
     """do something""" 

另外,如果你使用dict[candidate],那麼如果該鍵不存在於字典,它給KeyError。因此,爲了避免錯誤,檢查字典中是否存在元素的更好方法是使用get函數。

dict.get(candidate) == "true" 
+0

因此,在這種情況下,如果條件返回「true」,那麼將檢查下一個候選條件是否爲此條件,如果失敗,則控制移動到else語句中?我以爲我已經實施了這個確切的事情無濟於事,但將再次嘗試 – user3058703

+0

是的,你是對的。我想這就是你想要做的。如果條件爲真,繼續將停止當前迭代中的進一步執行,否則它將轉到else部分。 – Charul

+0

作品 - 謝謝! – user3058703

0

基本上,如果當前列表值在字典中,你想要去列表的下一個迭代?如果是這樣,用pass(不帶引號)替換「」「next」「」。

1

注意,字典是保留字,所以用不同的名稱,以避免出現問題

candidates = ['abacus', 'ball', 'car'] 
my_dictionary = {} 

for candidate in candidates: 
    if candidate not in my_dictionary: 
     """do something""" 
     break # exit the loop 
相關問題