繁体   English   中英

从列表中删除重复项

[英]Remove duplicates from the list

我有一个主列表,用于存储可以随时添加到主列表的不同列表。 我的问题是从主列表中的列表中删除相同的值。 因此,例如:

初始列表列表:

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
  ('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
 ['r', 'q']]

所需退货:

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
  ('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q'], ['r', 'q']]

第二个例子

初始:

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
  ('diamond', 'q')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
 [('not', r'), 'q']]

返回

[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q')],
 [('not', 'p'), 'q'], ['p', 'q'], ['q'], [('not', r'), 'q']]

重要的是, 顺序必须相同,并且仅主列表中的列表不需要重复。 我已经看到了许多有关堆栈溢出的建议,但是它们都没有用,因为逐个元素地检查只会让我自己拥有“钻石”或“盒子”的价值。 实际上,我需要在其中完全添加('diamond','q')元组。 这个问题与类似的问题不同,因为我想在主列表中对单个列表进行排序。

from collections import OrderedDict

init_list = [[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'), ('diamond', 'q')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'], [('not', 'r'), 'q']]

uniq_list = [list(OrderedDict.fromkeys(l)) for l in init_list]

OrderedDict允许您创建一个有序集合,因为OrderedDict.fromkeys(l)返回一个字典,其中l保留键的顺序(并消除重复项)。 list(OrderedDict)仅将字典的键作为list返回。

您可以将此食谱用于OrderedSet ,然后

init_list = # your list of lists
uniq_list = [list(OrderedSet(l)) for l in init_list]

暂无
暂无

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

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