如何返回两个二维列表中不匹配的内容?

问题描述 投票:0回答:1

我有两个二维列表,其中有大量行,并且两个列表的大小长度不同。我在 df1 中的每一行中查找匹配项时遇到问题,并且只返回 df2 中的每一行的不匹配值。例如,df1[0] 在 df2[0] 中匹配 1,3,5,返回 17。df1[0] 在 df2[1] 中没有匹配,不返回任何内容或括号。 df1 和 df2 中的每一行依此类推。

我已经尝试过这些代码,但没有给我我想要的。

no_matches = []
for sublist1 in df1:
    for sublist2 in df2:
        no_match = [val for val in sublist2 if val not in sublist1]
        if no_match: no_matches.append(no_match)
print("no matches:", no_matches)

这是一个简短的例子(我的二维列表)

 df1 = [[1, 7, 3, 5], [2, 5, 14, 10]]
 df2 = [[1, 17, 3, 5], [34, 14, 74], [34, 3, 87], [25, 14, 10]]

转换为 3D 列表。

 no_match = 0: [[17], [], [34,87], []]
            1: [[1,3,17], [34,74], [], [25]]

可能的愿望(转换为二维列表并删除括号)如果可能

 no_match = [[17],[34,87],[1,3,17],[34,74],[25]]
python multidimensional-array
1个回答
0
投票

看来您对规则有一个例外“仅返回 df2 中每一行的不匹配值”。在示例中,您描述了如果 “df1[0] 在 df2[1] 中没有匹配项,则不返回任何内容”,但这违反了规则。如果这确实是一个例外,那么您需要将该例外添加到您的

if
语句中:

    if no_match and no_match != sublist2: 
        no_matches.append(no_match)

有了这个附加条件,您将获得所需的输出:

no matches: [[17], [34, 87], [1, 17, 3], [34, 74], [25]]
© www.soinside.com 2019 - 2024. All rights reserved.