2014-02-19 82 views
1
def only_evens(lst): 
    """ 
    Return a list of the lists in lst that contain only even integers. 

    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]]) 
    [[4, 0, 6], [2]] 
    """ 
    even_lists = [] 
    condition = True 

    for sublist in lst: 
     for num in sublist: 
      if num % 2 != 0: 
       condition = condition and False 
     if condition == True: 
      even_lists.append(sublist) 

    return even_lists 

我不明白爲什麼這會一直返回一個空字符串?直觀地說,這是有道理的?非常感謝您的幫助。我一直在這方面停留太久。Python - 返回僅包含整數的lst中的列表列表?

編輯:非常感謝大家!我現在得到它:)。

回答

1

您正在初始化condition以外的循環。這應該被重新初始化爲每個子表和condition = condition and False將始終評估爲False,本來應該condition = False

for sublist in lst: 
    condition = True 
    for num in sublist: 
     if num % 2 != 0: 
      condition = False 
      break 

這可以用all函數來完成,像這樣

return [sublist for sublist in lst if all(item % 2 == 0 for item in sublist)] 

採樣運行

def only_evens(lst): 
    return [sublist for sublist in lst if all(item % 2 == 0 for item in sublist)] 

print only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]]) 
# [[4, 0, 6], [2]] 
+0

@thefourtheye點擊複選標記u這個職位。接受這個答案。謝謝 – Kulbir

1

thefourtheye回答了喲你的問題。但利用這一點,它可以更「簡單」:

[sublst for sublst in lst if all(x%2 == 0 for x in sublst)] 
0

的問題是condition and False

蟒提示:

>>> True and False 
False 
>>> False and False 
False 

而且我重做使用yield語句的代碼, for..else循環控制魔術,只是爲了好玩:

def only_evens(lst): 
    for sub_lst in lst: 
     for num in sub_lst: 
      if num % 2 != 0: 
       break 
     else: 
      yield sub_lst 

print list(only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]]))