从列表中删除重复项
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']]
想要return:
[[('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']]
return
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q')],
[('not', 'p'), 'q'], ['p', 'q'], ['q'], [('not', r'), 'q']]
重要的是,顺序必须相同并且只有主列表中的列表不需要重复。我看过很多关于堆栈溢出的建议,但其中 none 有效,因为逐个元素检查只会给我留下 'diamond' 或 'box' 值。实际上我需要完整添加 ('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)
returns 一个包含来自 l
的键的字典保留它们的顺序(并消除重复项)。 list(OrderedDict)
只是 returns 字典的键作为 list
.
您可以使用 this recipe 作为 OrderedSet
然后
init_list = # your list of lists
uniq_list = [list(OrderedSet(l)) for l in init_list]
我有一个主列表来存储可以随时添加到主列表的不同列表。我遇到的问题是从主列表的列表中删除相同的值。例如:
列表的初始列表:
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
['r', 'q']]
想要return:
[[('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']]
return
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q')],
[('not', 'p'), 'q'], ['p', 'q'], ['q'], [('not', r'), 'q']]
重要的是,顺序必须相同并且只有主列表中的列表不需要重复。我看过很多关于堆栈溢出的建议,但其中 none 有效,因为逐个元素检查只会给我留下 'diamond' 或 'box' 值。实际上我需要完整添加 ('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)
returns 一个包含来自 l
的键的字典保留它们的顺序(并消除重复项)。 list(OrderedDict)
只是 returns 字典的键作为 list
.
您可以使用 this recipe 作为 OrderedSet
然后
init_list = # your list of lists
uniq_list = [list(OrderedSet(l)) for l in init_list]