简体   繁体   English

使用列表中包含的列表删除重复的元组

[英]Remove duplicated tuples with included lists from list

i have a list with tuples: 我有一个元组列表:

managed_list = [ ('a', [1,2]), ('a', [1,2]), ('b', [2,2]), ('b', [2,2])]

need to get: 需要得到:

managed_list = [ ('a', [1,2]), ('b', [2,2]) ]

tried: 尝试:

seen = set()
[[n for n in x if n not in seen and not seen.add(n)] for x in managed_list]

getting: 得到:

TypeError: unhashable type: 'list'

Right, you can't use a list or a structure containing a list (or another unhashable type) in a set . 是的,您不能在set使用包含list (或其他不可变类型)的list或结构。 Without changing your input structure, you could use itertools.groupby and then just discard the iterator through the duplicates: 在不改变输入结构的情况下,可以使用itertools.groupby ,然后通过重复项丢弃迭代器:

import itertools
uniques = [x[0] for x in itertools.groupby(sorted(managed_list))]

Incidentally if it were not for the unhashable key issue (eg if the lists were tuples instead), your expression could be simplified to: 顺便说一句,如果它不是针对不可用的密钥问题(例如,如果列表是元组),则表达式可以简化为:

list(set(managed_list))

You do not need the extra code in the list comprehension for this. 您不需要列表推导中的额外代码。

You can also use collections.OrderedDict to remove duplicate keys. 您还可以使用collections.OrderedDict删除重复的键。

>>> from collections import OrderedDict
>>> OrderedDict([ ('a', [1,2]), ('a', [1,2]), ('b', [2,2]), ('b', [2,2])]).items()
[ ('a', [1,2]), ('b', [2,2]) ]

Keep in mind that in case of duplicate keys, the right-most entry will be the one included in the output. 请记住,在重复键的情况下,最右边的条目将是输出中包含的条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM