从python的dicts列表中选择最高值

时间:2013-06-21 03:00:59

标签: python list numpy

在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}]

     ]

我需要从每个dicts列表中检索最高的'y'值...所以结果列表将包含:

 Z = [(4, 7), (3,13), (1,20)]

在A中,'x'是每个词典的关键,而'y'是每个词典的值。

有什么想法吗?谢谢。

5 个答案:

答案 0 :(得分:6)

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

<强>更新

建议 - J.F. Sebastian:

from operator import itemgetter
Z = [itemgetter(*'xy')(max(lst, key=itemgetter('y'))) for lst in A]

答案 1 :(得分:5)

我使用itemgettermax的{​​{1}}参数:

key

答案 2 :(得分:4)

[max(((d['x'], d['y']) for d in l), key=lambda t: t[1]) for l in A]

答案 3 :(得分:2)

已经解决了您所陈述的问题,但我建议您更改基础数据结构。对于诸如 point 之类的小元素,元组要快得多。如果您愿意,可以使用namedtuple保留字典的清晰度。

>>> from collections import namedtuple
>>> 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}]

     ]

制作Point namedtuple很简单

>>> Point = namedtuple('Point', 'x y')

这就是实例的样子

>>> Point(x=1, y=0) # Point(1, 0) also works
Point(x=1, y=0)
然后

A看起来像这样

>>> A = [[Point(**y) for y in x] for x in A]
>>> A
[[Point(x=1, y=0), Point(x=2, y=3), Point(x=3, y=4), Point(x=4, y=7)], 
 [Point(x=1, y=0), Point(x=2, y=2), Point(x=3, y=13), Point(x=4, y=0)], 
 [Point(x=1, y=20), Point(x=2, y=4), Point(x=3, y=0), Point(x=4, y=8)]]

现在这样工作要容易得多:

>>> from operator import attrgetter
>>> [max(row, key=attrgetter('y')) for row in A]
[Point(x=4, y=7), Point(x=3, y=13), Point(x=1, y=20)]

为了保留元组的速度优势,最好通过索引访问:

>>> from operator import itemgetter
>>> [max(row, key=itemgetter(2)) for row in A]
[Point(x=4, y=7), Point(x=3, y=13), Point(x=1, y=20)]

答案 4 :(得分:0)

result=[]
for item in a:
    new = sorted(item, key=lambda k: k['y'],reverse=True)
    result.append((new[0]['x'],new[0]['y']))
print(result)

注意-这不是有效的方法,但这是获得所需结果的一种方法。