[英]Comparing a list to another nested list in python
Good day coders, I have 2 lists:美好的一天编码员,我有 2 个列表:
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).我正在尝试从列表 A 中获取项目,然后遍历列表 B 并查看项目 A 是否在列表 B 中(列表 B 有一个嵌套列表)。 i tried to use a for loop like so:我尝试像这样使用 for 循环:
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:也许pandas.explode
帮助:
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.如果您确实想要这样做,请创建一个值列表,这些值在两个列表中并且在 A 中但不在 B 中,并通过 list(dict.fromkeys(mylist)) 消除重复项,其中 mylist 是考虑的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.