删除重复的元组和列表中的列表

时间:2018-11-21 11:43:47

标签: python list tuples list-comprehension

我有一个元组列表和python中的列表:

gammagammalambda = [[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('r', 'u'), ('p', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]

哪里

[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]]

相同
[[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]

所以现在,我想删除这些双重元素,以便拥有

[[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]

为此,我想使用列表理解,并且尝试了

main_set = set(tuple(frozenset(innermost_list) for innermost_list in sublist) for sublist in gammagammalambda)

但是我得到了错误:

TypeError: unhashable type: 'list'

希望,你可以帮助我。

2 个答案:

答案 0 :(得分:3)

以下是一种替代方法:

gammagammalambda = [[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
                    [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]],
                    [[('r', 'u'), ('p', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
                    [[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]

d = {frozenset(e[0]) : e for e in reversed(gammagammalambda)}
result = list(d.values())

print(result)

输出

[[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]

创建一个字典,其中的键表示必须唯一的值,对于将每个gammagammalambda元素都设置为值的每个键,最后,唯一值就是字典d的值。 / p>

或更简单的替代方法:

gammagammalambda = [[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
                    [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]],
                    [[('r', 'u'), ('p', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
                    [[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]


seen = set()
result = []
for e in gammagammalambda:
    key = frozenset(e[0])
    if key not in seen:
        result.append(e)
        seen.add(key)

print(result)

输出

[[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]], [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]

答案 1 :(得分:0)

类似于this answerlist是不可哈希的,tuplefrozenset 可哈希的。

您可以相应地定义一个“唯一性密钥”,并使用itertools unique_everseen recipe(在第三方库中也可以使用toolz.uniquemore_itertools.unique_everseen):

from more_itertools import unique_everseen

L = [[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
     [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]],
     [[('r', 'u'), ('p', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
     [[('r', 'w'), ('p', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]

def unique_everseen(x):
    return frozenset(x[0]), tuple(map(tuple, x[1][0]))

res = list(unique(L, key=unique_key))
[[[('p', 'u'), ('r', 'w')], [[[], ['q', 's'], ['t', 'v'], []]]],
 [[('p', 'w'), ('r', 'u')], [[[], ['q', 's'], ['t', 'v'], []]]]]