新手问题。
假设我有一个嵌套词典列表。
a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
{"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}]
我想要的是移动每个副本的singularis条目,其中value1,value3和value4匹配。结果应该是这样的:
b = [{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
{"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie}]
原始列表a应该保留在原始状态中。
答案 0 :(得分:2)
最近有一个类似的问题。试试这个entry。
事实上,你问过这个问题:“假设存在多个条目,其中value3和value4与其他嵌套字典相同。我怎样才能快速轻松地找到并删除那些重复的字典。”
这听起来像是一回事,对吧?
编辑:自由地窃取Alex的代码,它看起来像这样:
import itertools
import pprint
import operator
alpha, charlie, norway, england = range(4)
a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
{"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423213121, "value3": england, "value4": alpha}]
getvals = operator.itemgetter('value1', 'value3', 'value4')
a.sort(key=getvals)
b = [g.next() for _, g in itertools.groupby(a, getvals)]
pprint.pprint(b)
结果是:
[{'value1': 1234, 'value2': 23423423421L, 'value3': 2, 'value4': 1},
{'value1': 1398, 'value2': 23423412221L, 'value3': 3, 'value4': 0}]