簡體   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