【问题标题】:Checking the contents of a python list检查 python 列表的内容
【发布时间】:2026-02-22 08:55:01
【问题描述】:

使用python 2.7.4

假设我有一个列表

list = ['abc', 'def']

我想看看它是否包含某些东西。所以我尝试:

 [IN:] 'abc' in list
[OUT:] True
 [IN:] 'def' in list
[OUT:] True
 [IN:] 'abc' and 'def' in list
[OUT:] True

但是当我 list.pop(0) 并重复最后一次测试时:

 [IN:] 'abc' and 'def in list
[OUT:] True

即使:

list = ['def']

有人知道为什么吗?

【问题讨论】:

    标签: python list collections conditional-statements


    【解决方案1】:

    那是因为:

    abc' and 'def' in list
    

    相当于:

    ('abc') and ('def' in list) #Non-empty string is always True
    

    使用'abc' in list and 'def' in list 或者对于多个项目,您也可以使用all()

    all(x in list for x in ('abc','def'))
    

    不要使用list作为变量名,它是一个内置类型。

    【讨论】:

    • 是的,列表只是为了演示目的。谢谢!