假设我有:
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)]
