如果值为True,则追加到Python中的新列表

如果值为True,则追加到Python中的新列表,python,Python,我正在尝试创建一个函数,该函数返回一个列表的副本,其中删除了非true元素。我试着这样做: def compact(lst): """Return a copy of lst with non-true elements removed. >>> compact([0, 1, 2, '', [], False, (), None, 'All done']) [1, 2, 'All done'] """

我正在尝试创建一个函数,该函数返回一个列表的副本,其中删除了非true元素。我试着这样做:

def compact(lst):
"""Return a copy of lst with non-true elements removed.

    >>> compact([0, 1, 2, '', [], False, (), None, 'All done'])
    [1, 2, 'All done']
"""
new_list = []
for element in lst:
    if element == True:
        new_list.append(element)

return new_list 
但是,当使用提供的测试时:

compact([0, 1, 2, '', [], False, (), None, 'All done'])

它只返回[1],而不是预期的[1,2,'All Done']。如果我只是删除了条件值,函数将打印每个值,因此逻辑检查某个值是否为真值似乎有问题。

只需从代码中删除
==True

def compact(lst):
    """Return a copy of lst with non-true elements removed.
    
    >>> compact([0, 1, 2, '', [], False, (), None, 'All done'])
    [1, 2, 'All done']
    """
    new_list = []
    for element in lst:
        if element:
            new_list.append(element)

    return new_list 
    
compact([0, 1, 2, '', [], False, (), None, 'All done'])

要了解原因,请尝试运行类似于
1==True
2==True

的代码,您将True和
True
混淆了
返回[x for x in lst if x]
您可以只使用
if element:
而不是
if element==True:
。问题在于布尔值
True
只是“truthy”值的一种类型。如果你感到困惑,你并不孤单。Python有一个布尔类型,但也有一个语义,允许任意值有时作为布尔值使用。这是有原因的,但当你第一次学习这门语言时,很难找到一个好的思维模式。谢谢大家!现在看起来非常明显,但有一段时间让我很沮丧