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

标签 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

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

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

最佳答案

您正在循环外初始化条件。应该为每个子列表重新初始化,并且 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]]

关于Python - 返回 lst 中仅包含整数的列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21871737/

相关文章:

python - 用星号python分割字符串

python - 初学者python设置交集错误

mysql - 如何使用 for 循环将新字段添加到文档索引 Lucene 中。

python - 在 Python 中一次更改列表中的多个项目

c# - 如何根据另一个列表中的两个属性创建一个 List<int>?

linux - 如何在for循环中调用变量作为变量名和变量值

html - For 循环正在添加一个选项卡本身

python - xmpppy 和 Facebook 聊天集成

python - python中2个列表的线性回归

python - 数值求解非线性方程 - Python