简体   繁体   中英

Pythonic way of checking if several elements are in a list

I have this piece of code in Python:

if 'a' in my_list and 'b' in my_list and 'c' in my_list:
    # do something
    print my_list

Is there a more pythonic way of doing this?

Something like (invalid python code follows):

if ('a', 'b', 'c') individual_in my_list:
    # do something
    print my_list
if set("abc").issubset(my_list):
    # whatever

The simplest form:

if all(x in mylist for x in 'abc'):
    pass

Often when you have a lot of items in those lists it is better to use a data structure that can look up items without having to compare each of them, like a set .

You can use set operators:

if set('abc') <= set(my_list):
    print('matches')

superset = ('a', 'b', 'c', 'd')
subset = ('a', 'b')
desired = set(('a', 'b', 'c'))

assert desired <= set(superset) # True
assert desired.issubset(superset) # True
assert desired <= set(subset) # False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM