简体   繁体   中英

To check whether at least one list contains a specific element

Could someone please tell me what is the shortest way to write this logic?

I have two lists as list_one and list_two containing some letters. If none of these two lists contain 'B', I need to print(True). The snippet I have written works, but I am curious to know whether there is a pythonic way to write this instead of repeating 'B' twice in the same line.

    list_one = ['A', 'K', 'L', 'J']
    list_two = ['N', 'M', 'P', 'O']
    
    if 'B' not in list_one and 'B' not in list_two:
        print('True')

Thanks in advance and any help would be greatly appreciated.

Well, you can do that (even though I think your way is the best):

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']
    
if 'B' not in (set(list_one) & set(list_two)):
    print('True')

Or:

if 'B' not in list_one + list_two:
        print('True')

You can try the all function if it is more readable for you.

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']

print(all('B' not in current_list for current_list in [list_one, list_two]))

We have sets in Python and they are really fast compared to lists.

Here some features about sets.

  • Sets are unordered.
  • Set elements are unique.
  • Duplicate elements are not allowed in sets.

Therefore you can search the item in a common set.

list_one = ['A', 'K', 'L', 'J']
list_two = ['N', 'M', 'P', 'O']

if 'B' not in set(list_one + list_two)
    print('True')

Bonus: You can use extend method to speed up list concatenation

set( list_one.extend( list_two ))

A different way of doing this is putting all lists in a Pandas DataFrame first:

import pandas as pd
df = pd.DataFrame(list(zip(list_one, list_two)), columns =['l1', 'l2']) 

Then you could check easily if the character B is absent by returning a True. The double .any() is to check rows and columns:

~df.isin(['B']).any().any()

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