首页 > 解决方案 > 从多个列表和列表列表中获取唯一对象。然后使用所有列表中的唯一对象创建一个新列表

问题描述

我的数据集混合了列表和列表列表。所以我需要从列表或列表列表中获取唯一对象,但找不到任何成功。输入数据集如下:

[[1, 2, 39], [1, 2, 39], [3], [[3], [4, 14, 63, 65], [66, 68, 82, 94]], [[5 , 8, 31, 34], [36, 37, 42, 44], [55]], [6, 91], [[7, 35, 60, 71], [73, 83, 95, 98]] , [[5, 8, 31, 34], [36, 37, 42, 44], [55]], [9, 72], [[10, 22, 30, 32], [38, 51, 56 , 87], [89, 92]], [11], [12], [13, 90], [[4, 14, 63, 65], [66, 68, 82, 94]]]

输出要求:

[[1, 2, 39], [3], [4, 14, 63, 65], [66, 68, 82, 94], [5, 8, 31, 34], [36, 37, 42, 44], [55], [6, 91], [7, 35, 60, 71], [73, 83, 95, 98], [9, 72], [10, 22, 30, 32], [ 38, 51, 56, 87], [89, 92], [11], [12], [13, 90], [66, 68, 82, 94]]

abc=[]
for x in pool:
    if x not in abc:
        abc.append(x)

我不明白如何选择由列表和列表列表组成的列表的不同对象。任何帮助将不胜感激。

我咨询了多个来源,但没有解决我的问题。其中少数如下:

列表中的唯一列表

https://www.geeksforgeeks.org/python-get-unique-values-list/

从多个列表中创建唯一的对象列表

标签: python

解决方案


您可以使用生成器将列表展平,然后循环生成的值并在未看到时添加到结果中。就像是:

def flatten(l):
    for item in l:
        if isinstance(item[0], list):
            yield from flatten(item)
        else:
            yield item

seen = set()
unique = [] 

for l in flatten(l):
    if tuple(l) in seen:
        continue
    seen.add(tuple(l))
    unique.append(l)

print(unique)

结果

[[1, 2, 39],
 [3],
 [4, 14, 63, 65],
 [66, 68, 82, 94],
 [5, 8, 31, 34],
 [36, 37, 42, 44],
 [55],
 [6, 91],
 [7, 35, 60, 71],
 [73, 83, 95, 98],
 [9, 72],
 [10, 22, 30, 32],
 [38, 51, 56, 87],
 [89, 92],
 [11],
 [12],
 [13, 90]]

推荐阅读