如何在同一个二维列表中返回相似的匹配项

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

我有一个 2d 列表,我试图在每个子列表中返回 2 个以上的匹配项,以及同一 2d 列表中的任何列(如果有意义的话)。然后我想删除二维列表中的重复项。如果可能的话。 下面是我的二维列表。

Df = [[2,4,6,8],[2,4,6,12,15], 
[2,4,8,17,24],[3,7,17,24], 
[5,10,15,23],[8,10,43], 
[4,5,10,55],[4,8,15,16,17,56]]


Df2 = [[[2,4,6,8], 
[2,4,6,12,15],[2,4,8,17,24]],
[[[2,4,6,8],[2,4,8,17,24]], 
[[[2,4,6,8]], 
[[[4,8,15,16,17,24]]]

删除 df2 的重复项

 Df3 = [[2,4,6,8], 
 [2,4,6,12,15],[2,4,8,17,24], 
 [4,8,15,16,17,24]]
python dataframe list multidimensional-array jupyter-notebook
1个回答
0
投票

我建议使用

Df
,返回具有超过 2 个共同元素的子列表,然后从第二个列表 DF2 中删除重复项。

最后显示结果

Df = [[2,4,6,8],[2,4,6,12,15], 
[2,4,8,17,24],[3,7,17,24], 
[5,10,15,23],[8,10,43], 
[4,5,10,55],[4,8,15,16,17,56]]

def common_elements_count(list1, list2):
    return len(set(list1) & set(list2))

result = []
for i in range(len(Df)):
    for j in range(i+1, len(Df)):
        if common_elements_count(Df[i], Df[j]) > 2:
            result.append(Df[i])
            result.append(Df[j])

# Duplicate remove
result = [list(x) for x in set(tuple(sorted(sublist)) for sublist in result)]

print("Result from Df:", result)

Df2 = [[[2,4,6,8], [2,4,6,12,15],[2,4,8,17,24]],
[[[2,4,6,8],[2,4,8,17,24]], 
[[[2,4,6,8]], 
[[4,8,15,16,17,24]]]]

# Flatten Df2 and remove duplicates
def flatten(lst):
    flat_list = []
    for sublist in lst:
        if isinstance(sublist[0], list):
            for item in sublist:
                flat_list.append(item)
        else:
            flat_list.append(sublist)
    return flat_list

flat_df2 = flatten(flatten(Df2))
unique_df2 = [list(x) for x in set(tuple(sorted(sublist)) for sublist in flat_df2)]

print("Unique values from Df2:", unique_df2)
© www.soinside.com 2019 - 2024. All rights reserved.