[英]Remove duplicates from the list
I have a main List to store different lists that could be added at any time to main List. 我有一个主列表,用于存储可以随时添加到主列表的不同列表。 The problem I have is to delete the same values from the lists in the main list.
我的问题是从主列表中的列表中删除相同的值。 So for example:
因此,例如:
Initial List of lists: 初始列表列表:
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
['r', 'q']]
Desired return: 所需退货:
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q'], ['r', 'q']]
Second example 第二个例子
Initial: 初始:
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
('diamond', 'q')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
[('not', r'), 'q']]
return 返回
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q')],
[('not', 'p'), 'q'], ['p', 'q'], ['q'], [('not', r'), 'q']]
Importantly, order must be the same and only the list inside the main list need not to have duplicates. 重要的是, 顺序必须相同,并且仅主列表中的列表不需要重复。 I have seen many suggestions on stack overflow but none of them work because checking element by element would just leave me with 'diamond' or 'box' values on its own.
我已经看到了许多有关堆栈溢出的建议,但是它们都没有用,因为逐个元素地检查只会让我自己拥有“钻石”或“盒子”的价值。 Where in fact I need
('diamond','q')
tuple to be added in full. 实际上,我需要在其中完全添加
('diamond','q')
元组。 This question is different to similar questions because I want to sort a single list inside the main list. 这个问题与类似的问题不同,因为我想在主列表中对单个列表进行排序。
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
allows you to create an ordered set since OrderedDict.fromkeys(l)
returns a dictionary with keys from l
preserving their order (and eliminating duplicates). OrderedDict
允许您创建一个有序集合,因为OrderedDict.fromkeys(l)
返回一个字典,其中l
保留键的顺序(并消除重复项)。 list(OrderedDict)
simply returns the dict's keys as a list
. list(OrderedDict)
仅将字典的键作为list
返回。
You can use this recipe for an OrderedSet
and then 您可以将此食谱用于
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.