gpt4 book ai didi

python - 如何消除一组列表中的重复元素和回文?

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

假设我有:

a = [(0, 1), (0, 2), (3, 0)]
b = [(4, 5), (2, 0)]
c = [(2, 6), (5,3)]
lists = [a, b, c]

所以我需要一个函数来生成

list = [(0, 1), (0, 2), (3, 0), (4, 5),(2, 6), (5,3) ]

引用this问题 我已经能够删除重复的元素,但我不知道如何解决回文

最佳答案

你可以使用这样的东西。我使用了 frozenset 因为它允许被散列并且像 set 它不关心顺序 - 所以要注意你的回文和重复:

from iteration_utilities import unique_everseen
from itertools import chain

a = [(0, 1), (0, 2), (3, 0)]
b = [(4, 5), (2, 0)]
c = [(2, 6), (5,3)]
lists = [a, b, c]

示例运行:

>>> list(unique_everseen(chain.from_iterable(lists), key=frozenset))
[(0, 1), (0, 2), (3, 0), (4, 5), (2, 6), (5, 3)]

unique_everseen 的配方也可以从 itertools python documentation page 借用。如果您不需要外部模块。


如果您的项目包含超过 2 个元素,您可以将其用作 unique_everseen 函数。 (与配方略有不同):

def remove_duplicates_and_reversed(iterable):
seen = set()
for item in iterable:
if item not in seen:
seen.add(item) # takes care of duplicates
seen.add(item[::-1]) # takes care of reversed duplicates
yield item

>>> list(remove_duplicates_and_reversed(chain.from_iterable(lists)))
[(0, 1), (0, 2), (3, 0), (4, 5), (2, 6), (5, 3)]

关于python - 如何消除一组列表中的重复元素和回文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992343/

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