mar*_*ber -1 python sorting logic duplicates nested-lists
我有一个主List来存储可以随时添加到主List的不同列表.我遇到的问题是从主列表中的列表中删除相同的值.例如:
初步清单清单:
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
['r', 'q']]
Run Code Online (Sandbox Code Playgroud)
期望的回报:
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
('diamond', 'r')], [('not', 'p'), 'q'], ['p', 'q'], ['q'], ['r', 'q']]
Run Code Online (Sandbox Code Playgroud)
第二个例子
初始:
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'),
('diamond', 'q')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'],
[('not', r'), 'q']]
Run Code Online (Sandbox Code Playgroud)
返回
[[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q')],
[('not', 'p'), 'q'], ['p', 'q'], ['q'], [('not', r'), 'q']]
Run Code Online (Sandbox Code Playgroud)
重要的是,顺序必须相同,只有主列表中的列表不需要重复.我已经看到很多关于堆栈溢出的建议,但它们都不起作用,因为逐个元素检查会让我自己留下'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]
Run Code Online (Sandbox Code Playgroud)
OrderedDict允许您创建一个有序集,因为它OrderedDict.fromkeys(l)返回一个带有键的字典,l保留它们的顺序(并消除重复).list(OrderedDict)简单地将dict的键作为a返回list.