gpt4 book ai didi

具有嵌套列表/元组的 Python 操作(交集、联合、重复)可能吗?

转载 作者:太空宇宙 更新时间:2023-11-03 11:54:08 26 4
gpt4 key购买 nike

案例:

a = [(1,2),(2,3),(4,5),(1,6),(1,7)]b = [(5,2),(6,3),(4,5),(6,8),(1,9)]

如何删除第一个元组项的重复项?

a 的结果是:

[(1,2),(2,3),(4,5)]

b 的结果是:

[(5,2),(6,3),(4,5),(1,9)]

如何在不重复的情况下合并两者?:结果将是:

[(1,2),(2,3),(4,5),(5,2),(6,3)]

我怎样才能得到两者的交集?:结果将是:

[(1,2),(4,5)]

这有可能吗?

最好的问候克里斯

最佳答案

使用集合:

>>> seen = set()
>>> s1 = [x for x in a if x[0] not in seen and not seen.add(x[0])]
>>> seen = set()
>>> s2 = [x for x in b if x[0] not in seen and not seen.add(x[0])]
>>> s1
[(1, 2), (2, 3), (4, 5)]
>>> s2
[(5, 2), (6, 3), (4, 5), (1, 9)]

联盟:

>>> from itertools import chain
>>> seen = set()
>>> [x for x in chain(s1,s2) if x[0] not in seen and not seen.add(x[0])]
[(1, 2), (2, 3), (4, 5), (5, 2), (6, 3)]

十字路口:

>>> se1 = set(x[0] for x in s1)
>>> se2 = set(x[0] for x in s2)
>>> inter = se1 & se2
>>> inter
set([1, 4])
>>> seen = set()
>>> [x for x in chain(s1,s2) if x[0] in inter and x[0] not in seen
and not seen.add(x[0])]
[(1, 2), (4, 5)]

关于具有嵌套列表/元组的 Python 操作(交集、联合、重复)可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17432356/

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