简体   繁体   中英

Check if string present in multiple lists (python)

Hoping someone can advise on the most efficient way to check whether a set string is present in all of three given lists, and if so, set itemInAllLists to True.

Below is the general idea of what I'm trying to achieve.

item = 'test-element'

list_a = ['a','random','test-element']
list_b = ['light','apple','table']
list_c = ['car','field','test-element','chair']

itemInAllLists = False

if item in [list_a] and item in [list_b] and item in [list_c]:
   itemInAllLists = True

Have a look at the all built-in for Python, it will return True if all elements of an iterable is true.

If you put all your lists in a combined list you can dolist comprehension to check each list.

all(item in all_lists for all_lists in [list_a, list_b, list_c])

Update

As deceze mentions you don't have to do it this way, what you are doing works as well and might be easier to read. Using all or any might be better suited for more lists or when you create them dynamically.

For your code to work you just have to remove the brackets so the syntax is correct:

if item in list_a and item in list_b and item in list_c:
    pass

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