Home > database >  Comparing a list to another nested list in python
Comparing a list to another nested list in python

Time:07-20

Good day coders, I have 2 lists:

A = ['yes', 'red', 'car']
B = ['yes', ['yellow', 'red'], 'car']

I am trying to take items from list A and then loop through list B and see if item-A is in list B (List B is has a nested list). i tried to use a for loop like so:

for item in A:
    if item in B:
        print(item,'is a correct answer.')
    else:
        print(item,'is a wrong answer.')

desired output 3 correct answer and the list B to be empty because after fiding a match, items from list be get popped out:

yes is a correct answer
red is a correct answer
car is a correct answer
List B = []


pardon my question structure, i am new to this. and thanks for helping =)

CodePudding user response:

One approach to handle arbitrarily nested lists:

def flatten(x):
    for e in x:
        if isinstance(e, list):
            yield from flatten(e)
        else:
            yield e


A = ['yes', 'red', 'car']
B = ['yes', ['yellow', 'red'], 'car']

for bi in flatten(B):
    if bi in A:
        print(bi)

Output

yes
red
car

CodePudding user response:

Try this:

def flatten(lst):
    if not lst:
        return lst
    if isinstance(lst[0], list):
        return flatten(lst[0])   flatten(lst[1:])
    return lst[:1]   flatten(lst[1:])

A = ['yes', 'red', 'car']
B = ['yes', ['yellow', 'red'], 'car']
C = flatten(B)

for item in A:
    if item in C:
        print(item, 'is in list B')
    else:
        print(item, 'is not in list B')

Output:

yes is in list B
red is in list B
car is in list B

CodePudding user response:

You can also solve it without flattening:

  for item in B:
    if item in A:
      print(item,'is a correct answer.')
    elif isinstance(item, list):
        for nested_item in item:
            if nested_item in A:
                print(nested_item,'is a correct answer.')
            else:
                print(nested_item,'is a wrong answer.')
    else:
        print(item,'is a wrong answer.')

But note that this solution does not eliminate the duplicates. If you do want to do that create a list of values which are in both lists and which are in A but but not in B and eliminate the duplicates by list(dict.fromkeys(mylist)), where mylist is the considered list.

CodePudding user response:

Maybe pandas.explode helps:

import pandas as pd
A = ['yes', 'red', 'car', 'test']
B = ['yes', ['yellow', 'red'], 'car']

for item in A:
    print(item, item in pd.DataFrame(B).explode(0)[0].tolist())

Result:

yes True
red True
car True
test False
  • Related