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



假设我有:

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) ]

提到这个问题,我已经能够删除重复的元素,但我无法弄清楚如何解决回文

你可以使用这样的东西。我使用了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)]

如果你不想要外部模块,也可以从itertools python文档页面借用unique_everseen的配方。


如果你有超过 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)]

最新更新