[英]Python find max of index 1 & 2 in a list of list
在列表中
[
[[ 979, 2136, 3427, 2221]],
[[1497, 697, 2843, 721]],
[[2778, 2194, 3903, 2233]],
]
如此迭代
for line in lines:
for x1, y1, x2, y2 in line:
我想找到(x1 或 x2 以最大值為准)和(y1 y2 以最大值為准)的最大值
你可以這樣做:
[*map(lambda x: list(map(max, [x[0][:2], x[0][2:]])), mylist)]
[[2136, 3427], [1497, 2843], [2778, 3903]]
import sys
max_x, max_y = [-sys.maxsize,-sys.maxsize]
lines = [
[[979,2136,3427,2221]],
[[1497,697,2843,721]],
[[2778,2194,3903,2233]]
]
for line in lines:
for x1, y1, x2, y2 in line:
if max(x1,x2) > max_x:
max_x = max(x1,x2)
if max(y1,y2) > max_y:
max_y = max(y1,y2)
如果您的點只有正值,您可以將 max_x 和 max_y 初始化為 0。
我更喜歡 Nicolas 的答案的更詳細(但我認為也更易讀)的版本,它保留了for
循環並使用命名元組來獲得更有意義的 output:
from collections import namedtuple
Coordinate = namedtuple('Coordinate', ['x', 'y'])
lines = [[[ 979, 2136, 3427, 2221]], [[1497, 697, 2843, 721]], [[2778, 2194, 3903, 2233]]]
maximums = []
for line in lines:
for x1, y1, x2, y2 in line:
maximums.append(Coordinate(x=max(x1, x2), y=max(y1, y2)))
print(maximums)
# prints [Coordinate(x=3427, y=2221), Coordinate(x=2843, y=721), Coordinate(x=3903, y=2233)]
print([Coordinate(x=3427, y=2221), Coordinate(x=2843, y=721), Coordinate(x=3903, y=2233)])
# prints [(3427, 2221), (2843, 721), (3903, 2233)]
以下是如何找到每組的最大值:
ls1 = [[[ 979, 2136, 3427, 2221]],
[[1497, 697, 2843, 721]],
[[2778, 2194, 3903, 2233]]]
ls2 = [[max(a[0][:2]),
max(a[0][2:])]
for a in ls1]
print(ls2)
Output:
[[2136, 3427],
[1497, 2843],
[2778, 3903]]
要找到所有x
和y
的最大值:
ls1 = [[[ 979, 2136, 3427, 2221]],
[[1497, 697, 2843, 721]],
[[2778, 2194, 3903, 2233]]]
x = max([i for j in [a[0][:2] for a in ls1] for i in j])
y = max([i for j in [a[0][2:] for a in ls1] for i in j])
print(x, y)
Output:
2778 3903
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.