我有一个列表:
[{"name":"john","age":40,"class":10},
{"name":"john","age":45,"class":12},
{"name":"sam","age":10,"class":5},
{"name":"sam","age":11,"class":9},
{"name":"mark","age":50,"class: 8"}]
我想获得唯一名字的最大年龄。我怎么能用python做到这一点?
我的预期答案:
[{"name":"john","age":45,"class":12},
{"name":"sam","age":11,"class":9},
{"name":"mark","age":50,"class: 8"}]
答案 0 :(得分:4)
您可以使用itertools.groupby
执行此操作:
from itertools import groupby
data = [{"name":"john","age":40,"class":10},
{"name":"john","age":45,"class":12},
{"name":"sam","age":10,"class":5},
{"name":"sam","age":11,"class":9},
{"name":"mark","age":50,"class": 8}]
# groups dictionary by "name"
# takes max dictionary of each group by "age"
result = [max(list(g), key=lambda x: x['age']) for _, g in groupby(sorted(data, key=lambda x: x['name']), key=lambda x: x['name'])]
print(result)
哪个输出:
[{'name': 'john', 'age': 45, 'class': 12},
{'name': 'sam', 'age': 11, 'class': 9},
{'name': 'mark', 'age': 50, 'class': 8}]
答案 1 :(得分:2)
一个简单的for循环解决方案是
var _productServiceMock = new Mock< IProductService >();
结果:
A = [{"name":"john","age":40},
{"name":"john","age":45},
{"name":"sam","age":10},
{"name":"sam","age":11},
{"name":"mark","age":50}]
res = {}
for i in A:
if i['name'] not in res:
res[i['name']] = i['age']
else:
if res[i['name']] < i['age']:
res[i['name']] = i['age']
print res
答案 2 :(得分:1)
您能否进一步指明您的具体目标?你想保留这个结构吗?你想要字典中所有名字的列表吗? 你可以写一个这样的函数:
def maxdictlist(name,dictlist):
maxlst = []
for x in dictlist:
if x["name"] == name:
maxlst.append(x["age"])
return max(maxlst)
print(maxdictlist("john",A))
返回给定名称的最大值。 如果您可以保存您感兴趣的名称列表并希望保留结构,那么您也可以使用最大功能键来执行此类操作:
def ke(v,name):
if v["name"] == name: return v["age"]
else: return 0 #0 as default value
lst = []
names = ["john","sam"]
res = [max(A,key= lambda v:ke(v,name))) for name in names]
print(lst)
我会建议不要使用第二种方法。