解決您的陳述的問題已經給出,但我建議改變你的基礎數據結構。對於小型元素,例如點,元組要快得多。如果您願意,您可以使用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)]
你爲什麼標記此numpy的?此外,元組看起來像使用的數據結構要快得多,如果您願意,可以使用'collections.namedtuple'保留字典清晰度! – jamylak