Search code examples
pythonlistgenerator

Comparing entries in a list to another list


Using Python 3.9.5

a=['Apple', 'Orange', 'peaches']

b=[['Lettuce', 'Apple', 'eggs'],['potato', 'tomato', 'pepper']]

I want to compare for any values in a to b and if there is a match continue to the next list ( my program generates lists of key words) i want to compare the initial list "a" to the lists i have and if there is a match go next and if there is no match then do something like print that list.

this is what i tried, not working though

for i in b:
   if any(x in a for x in [b, c]):
      continue 
   else:
       print(#the current sublist)

i would like to say that with integers this code works but with lists or strings it doesn't, appreciate the feedback


Solution

  • a = ['Apple', 'Orange', 'peaches']
    b = [['Lettuce', 'Apple', 'eggs'], ['potato', 'tomato', 'pepper']]
    
    for el in b:
        if any([x in a for x in el]):
            print("ok")
        else:
            print(el)
    

    Returns:

    True
    False
    

    Explanation:

    1. First of all we iterate over b, so we have el = ['Lettuce', 'Apple', 'eggs'] on the first iteration.
    2. Next we create list of bools: [x in a for x in el]. We check are there elements of a in our current element el: [False, True, False] - for first element of b.
    3. Next we reduce our list of bools ([False, True, False]) to one bool using any()