Testing if multiple objects are in a list using one “in” statement (Python) [duplicate]

那年仲夏 提交于 2021-02-16 16:10:19

问题


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

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

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


回答1:


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()



回答2:


Make a list of your words and a generator expression checking if they are in the list:

words = ["word1", "word2", "etc"]
lst = [...]
if all((w in lst for w in words)):
    #do something

all checks if all values in an iterable are true. Because we use a generator this is still short-circuit optimized. Of course you can inline the list of words if it is not too big for a one-liner:

if all((w in lst for w in ["word1", "word2", "etc"])):
     ...



回答3:


You could do it like that:

if all(current_word in lst for current_word in (word, word1)):
  do x



回答4:


Note: Do not ever use this. It is simply here to illustrate "yet another" capability of python.

A less efficient solution:

>>> from itertools import permutations
>>> lis=[0,1,2,3,4]
>>> (1,2) in (z for z in permutations(lis,2)) #loop stops as soon as permutations(lis,2) yields (1,2)
True
>>> (1,6) in (z for z in permutations(lis,2))
False
>>> (4,2) in (z for z in permutations(lis,2))
True
>>> (0,5) in (z for z in permutations(lis,2))
False
>>> (0,4,1) in (z for z in permutations(lis,3))
True
>>> (0,4,5) in (z for z in permutations(lis,3))
False


来源:https://stackoverflow.com/questions/12271481/testing-if-multiple-objects-are-in-a-list-using-one-in-statement-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!