使用一个“输入"测试列表中是否有多个对象.声明(Python) [英] Testing if multiple objects are in a list using one "in" statement (Python)

查看:42
本文介绍了使用一个“输入"测试列表中是否有多个对象.声明(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Python检查以下所有项目在列表中

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

So I want to test whether both word and word1 are in the list lst. Of course, I could write:

if word in lst and word1 in lst:
    do x

但是我想知道我是否可以将该声明缩短为:

But I wondered if I could shorten that statement to something like:

if (word and word1) in lst:
    do x

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

Of course, that does not work, but is there anything effectively similar that will?

我尝试了以下操作,但是如您所见,它无法产生预期的结果.

I tried the following, but as you can see, it does not yield the desired result.

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

编辑:谢谢您的回答,我认为我现在有一个很好的主意.

Thank you for the answers, I think I have a pretty good idea of how to do this now.

推荐答案

答案是正确的(至少其中一个是正确的).但是,如果您正在执行遏制性检查并且不关心顺序(例如您的示例可能会建议),则真正的答案是您应该使用集合并检查子集.

The answers are correct (at least one of them is). However, if you're doing containment checks and don't care about order, like your example might suggest, the real answer is that you should be using sets, and checking for subsets.

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

这篇关于使用一个“输入"测试列表中是否有多个对象.声明(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆