gpt4 book ai didi

python - 合并两个嵌套列表并删除重复项

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:46 32 4
gpt4 key购买 nike

我想通过先删除重复项来合并两个嵌套列表。

list1 = [[1,2], [1,3], [3,5], [4,1], [9,6]]
list2 = [[1,2], [1,3], [3,5], [6,6], [0,2], [1,7], [7,7]]
results = [[1,2], [1,3], [3,5], [4,1], [9,6], [6,6], [0,2], [1,7], [7,7]]

我的代码:

not_in_list1 = set(list2) - set(list1)
results = list(list1) + list(not_in_list1)

错误:

TypeError: unhashable type: 'list'

是不是因为set操作不能在嵌套列表中使用?

谢谢

最佳答案

Is it because set operation cannot be used in nested lists?

是的,这是因为列表是可变的,所以列表在创建后可以更改,这意味着集合中使用的哈希可以更改。

但是元组是不可变的,因此您可以在集合中使用它们:

 list1 = [[1,2], [1,3], [3,5], [4,1], [9,6]]
list2 = [[1,2], [1,3], [3,5], [6,6], [0,2], [1,7], [7,7]]

将它们转换为元组:

 tuple1 = [tuple(l) for l in list1]

tuple2 = [tuple(l) for l in list2]

not_in_tuples = set(tuple2) - set(tuple1)

not_in_tuples 的结果:

 {(0, 2), (1, 7), (6, 6), (7, 7)}

并将它们组合回您想要的结果:

results = list1 + list(map(list, not_in_tuples))

产生:

[[1, 2], [1, 3], [3, 5], [4, 1], [9, 6], [0, 2], [1, 7], [7, 7], [6, 6]]

编辑

如果有兴趣在将两个列表加在一起后保留它们的顺序:

list1 = [[1,2], [1,3], [3,5], [4,1], [9,6]]
list2 = [[1,2], [1,3], [3,5], [6,6], [0,2], [1,7], [7,7]]

intersection = set(map(tuple, list1)).intersection(set(map(tuple, list2)))

result = list1 + [list(t) for t in map(tuple, list2) if t not in intersection]

产生:

[[1, 2], [1, 3], [3, 5], [4, 1], [9, 6], [6, 6], [0, 2], [1, 7], [7, 7]]

关于python - 合并两个嵌套列表并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752026/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com