繁体   English   中英

将列表与python中的另一个嵌套列表进行比较

[英]Comparing a list to another nested list in python

美好的一天编码员,我有 2 个列表:

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

我正在尝试从列表 A 中获取项目,然后遍历列表 B 并查看项目 A 是否在列表 B 中(列表 B 有一个嵌套列表)。 我尝试像这样使用 for 循环:

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

请原谅我的问题结构,我对此很陌生。 并感谢您的帮助 =)

处理任意嵌套列表的一种方法:

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)

输出

yes
red
car

尝试这个:

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')

输出:

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

也许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())

结果:

yes True
red True
car True
test False

您也可以在不展平的情况下解决它:

  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.')

但请注意,此解决方案不会消除重复项。 如果您确实想要这样做,请创建一个值列表,这些值在两个列表中并且在 A 中但不在 B 中,并通过 list(dict.fromkeys(mylist)) 消除重复项,其中 mylist 是考虑的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM