python - 从多个列表和列表列表中获取唯一对象。然后使用所有列表中的唯一对象创建一个新列表
问题描述
我的数据集混合了列表和列表列表。所以我需要从列表或列表列表中获取唯一对象,但找不到任何成功。输入数据集如下:
[[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/
解决方案
您可以使用生成器将列表展平,然后循环生成的值并在未看到时添加到结果中。就像是:
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]]
推荐阅读
- cypress - 如何使用柏树单击具有特定内容的 div 内的按钮?
- bash - Replcae \n 使用带有新行的 sed
- firebase - 云功能的安全规则
- reactjs - 如何在firebase存储中上传图片并使用swr-firestore在react中获取上传的图片url
- python - 如何限制每几秒刷新一次的页面中python beautifulsoup中抓取的数据
- c# - 使用 IIS 服务器部署和加载 DLL
- c++ - 严格的别名违规和内存地址
- mern - 为什么这个 mern 项目中的正则表达式标志无效?
- api - 无法得到会所 api/Complete api 的响应
- postgresql - 如何设置从本地 Postgresql DB 到 AWS RDS Postgresql DB 的复制