How to check if all of the following items are in

2019-01-07 06:35发布

I found, that there is related question, about how to find if at least one item exists in a list:
How to check if one of the following items is in a list?

But what is the best and pythonic way to find whether all items exists in a list?

Searching through the docs I found this solution:

>>> l = ['a', 'b', 'c']
>>> set(['a', 'b']) <= set(l)
True
>>> set(['a', 'x']) <= set(l)
False

Other solution would be this:

>>> l = ['a', 'b', 'c']
>>> all(x in l for x in ['a', 'b'])
True
>>> all(x in l for x in ['a', 'x'])
False

But here you must do more typing.

Is there any other solutions?

5条回答
对你真心纯属浪费
2楼-- · 2019-01-07 07:11

This is a different method:

Code:

def isAll(lis1, lis2):
    list = []
    for i in lis2:
        for ii in lis1:
            if i == ii:
                    list.append(True)
            else:
                    list.append(False)

    if list.count(True) == len(lis1):
        return True
    else:
        return False

lis1 = ["a","b","c"]
lis2 = ["a","b"]

isAll(lis1, lis2) #Output: False  
查看更多
可以哭但决不认输i
3楼-- · 2019-01-07 07:12

I would probably use set in the following manner :

set(l).issuperset(set(['a','b'])) 

or the other way round :

set(['a','b']).issubset(set(l)) 

I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...

查看更多
疯言疯语
4楼-- · 2019-01-07 07:19

I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using set literal syntax which has been backported to Python 2.7):

all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
#   or
{'a', 'b'}.issubset({'a', 'b', 'c'})
查看更多
放荡不羁爱自由
5楼-- · 2019-01-07 07:22

Operators like <= in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.

Use the equivalent and more clearly-named method, set.issubset. Note that you don't need to convert the argument to a set; it'll do that for you if needed.

set(['a', 'b']).issubset(['a', 'b', 'c'])
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-07 07:27

What if your lists contain duplicates like this:

v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']

Sets do not contain duplicates. So, the following line returns True.

set(v2).issubset(v1)

To count for duplicates, you can use the code:

v1 = sorted(v1)
v2 = sorted(v2)


def is_subseq(v2, v1):
    """Check whether v2 is a subsequence of v1."""
    it = iter(v1)
    return all(c in it for c in v2) 

So, the following line returns False.

is_subseq(v2, v1)
查看更多
登录 后发表回答