python - 使用一条 "in"语句测试列表中是否有多个对象 (Python)

标签 python python-3.x conditional-operator

<分区>

Possible Duplicate:
Python Check if all of the following items is in a list

所以我想测试 word 和 word1 是否都在列表 lst 中。 当然,我可以这样写:

if word in lst and word1 in lst:
    do x

但我想知道我是否可以将该语句缩短为:

if (word and word1) in lst:
    do x

当然,这行不通,但是有什么有效的类似方法吗?

我尝试了以下方法,但如您所见,它没有产生预期的结果。

>>> word in lst
True
>>> word1 in lst
True
>>> (word, word1) in lst
False

编辑:感谢您的回答,我想我现在很清楚如何做到这一点。

最佳答案

答案是正确的(至少有一个是)。但是,如果您正在进行包含检查并且不关心顺序,就像您的示例可能暗示的那样,真正的答案是您应该使用集合并检查子集。

words = {"the", "set", "of", "words"}
if words <= set_of_words:
   do_stuff()

关于python - 使用一条 "in"语句测试列表中是否有多个对象 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271481/

相关文章:

c++ - 条件运算符语法

go - if else语句如何做单行?

javascript - 如何使用 if...else 子句重写它?

python - 运行时警告 - Greenlet.greenlet 大小已更改?

python - Pytest - 模拟模拟的嵌套属性函数/方法的副作用

python - 将列表中的项目添加到另一个列表中的字典

python - 如何使用map reduce识别炎热的天气?

初始化字典的 Python KeyError 异常

python - 传递CSRF token

python - 就地自定义对象使用 __getitem__ python 3.5 与 python 3.6 解包不同的行为