在一系列dicts列表中:
A = [
[{'x': 1, 'y': 0}, {'x': 2, 'y': 3}, {'x': 3, 'y': 4}, {'x': 4, 'y': 7}],
[{'x': 1, 'y': 0}, {'x': 2, 'y': 2}, {'x': 3, 'y': 13}, {'x': 4, 'y': 0}],
[{'x': 1, 'y': 20}, {'x': 2, 'y': 4}, {'x': 3, 'y': 0}, {'x': 4, 'y': 8}]
]
Run Code Online (Sandbox Code Playgroud)
我需要从每个dicts列表中检索最高的'y'值...所以结果列表将包含:
Z = [(4, 7), (3,13), (1,20)]
Run Code Online (Sandbox Code Playgroud)
在A中,'x'是每个字典的关键,而'y'是每个字典的值.
有任何想法吗?谢谢.
max接受可选key参数.
A = [
[{'x': 1, 'y': 0}, {'x': 2, 'y': 3}, {'x': 3, 'y': 4}, {'x': 4, 'y': 7}],
[{'x': 1, 'y': 0}, {'x': 2, 'y': 2}, {'x': 3, 'y': 13}, {'x': 4, 'y': 0}],
[{'x': 1, 'y': 20}, {'x': 2, 'y': 4}, {'x': 3, 'y': 0}, {'x': 4, 'y': 8}]
]
Z = []
for a in A:
d = max(a, key=lambda d: d['y'])
Z.append((d['x'], d['y']))
print Z
Run Code Online (Sandbox Code Playgroud)
UPDATE
建议 - JF Sebastian:
from operator import itemgetter
Z = [itemgetter(*'xy')(max(lst, key=itemgetter('y'))) for lst in A]
Run Code Online (Sandbox Code Playgroud)
我会用itemgetter和max的key说法:
from operator import itemgetter
pair_getter = itemgetter('x', 'y')
[pair_getter(max(d, key=itemgetter('y'))) for d in A]
Run Code Online (Sandbox Code Playgroud)