2016-10-11 98 views
2

我試圖找到變量是列表中任何列表的元素。如果它是其中任何一個的元素,那麼我使用continue移動到下一個塊。如果它不是任何列表的成員,我想然後在列表中創建一個新列表,並將該變量作爲該列表的唯一條目。檢查Python for循環的所有迭代中是否有錯

我問的原因是因爲無論if語句是否滿意,或者沒有任何其他迭代得到滿足,兩種情況都會看到相同的結果,即通過此塊的延續。

for group in groups: 
    if point in group: 
     continue 
    else: 

     # if point not an element of any group, 
      create group in groups with variable as only element 

更新:

將這項工作?有更簡潔的方法來做到這一點嗎?

for group in groups: 
    if point in group: 
     groupCheck = 1 
    else: 
     pass 
if not groupCheck: 
    # Create a new list including point 
+0

問題是,你在一個小組中識別出來後在做什麼?如果沒有,只需在找到它之後再返回。這確實應該是兩個函數:'find'和'add'。 – GManNickG

回答

4

反向你的邏輯,並使用for循環的else子句來創建新組。

for group in groups: 
    if point in group: 
    break 
else: 
    create_new_group(point) 

或者只是使用any()

if not any(point in group for group in groups): 
    create_new_group(point) 
+0

這兩個建議看起來非常好:)謝謝Ignacio – McLeodx

1

爲什麼不把if語句放在循環之外?

found = False 

for group in groups: 
    if point in group: 
     found = True 
     break 

if not found: 
    groups.append([point]) 
+0

這是一個很好的觀點,謝謝。 – eeScott

1

做一個功能。

def check_matches(point, groups): 
    for group in groups: 
     if point in group: 
      return true 
    return false 

if not check_matches(point, groups): 
    groups.append([point]) 

你可以把它這個簡單,這取決於你正在嘗試與此有關呢,還是打造成爲一個更復雜的功能是:

def get_groups(point, groups): 
    if not check_matches(point, groups): 
     groups.append([point]) 
    return groups 

groups = get_groups(point, groups) 

有簡單的列表理解的事情可以做在這裏,但鑑於你對Python的新鮮感,我不推薦他們。這是一個可以讓你感到困惑的方式,並且在將來犯更多的錯誤。

1

嘗試使用內置的any()函數。

if not any(point in group for group in groups): 
    groups.append([point])