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.')
pardon my question structure, i am new to this. and thanks for helping =)
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
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
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
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.
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.