Python - 返回lst中仅包含整数的列表列表?

时间:2014-02-19 05:21:13

标签: python list for-loop nested-forms nested-loops

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

我不明白为什么这会一直返回一个空字符串?直观地说,这有道理吗?非常感谢您的帮助。我一直坚持这个问题太久了。

编辑:非常感谢你们!我现在明白了:)。

3 个答案:

答案 0 :(得分: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]]

答案 1 :(得分:0)

thefourtheye已经回答了你的问题。但是使用它,它更“简单”:

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

答案 2 :(得分:0)

问题是condition and False

在python提示符上:

>>> 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]]))