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

时间:2017-02-02 00:29:18

标签: python python-3.x

让我说我有:

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问题我已经能够删除重复的元素,但我无法弄清楚如何解决回文

1 个答案:

答案 0 :(得分:5)

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