alist = [(1,3),(2,5),(2,4),(7,5)]
我需要获取元组中每个位置的最小最大值。
Fox示例: alist的预期输出是
min_x = 1
max_x = 7
min_y = 3
max_y = 5
有简单的方法吗?
答案 0 :(得分:60)
map(max, zip(*alist))
首先解压缩您的列表,然后找到每个元组位置的最大值
>>> alist = [(1,3),(2,5),(2,4),(7,5)]
>>> zip(*alist)
[(1, 2, 2, 7), (3, 5, 4, 5)]
>>> map(max, zip(*alist))
[7, 5]
>>> map(min, zip(*alist))
[1, 3]
这也适用于列表中任何长度的元组。
答案 1 :(得分:8)
>>> from operator import itemgetter
>>> alist = [(1,3),(2,5),(2,4),(7,5)]
>>> min(alist)[0], max(alist)[0]
(1, 7)
>>> min(alist, key=itemgetter(1))[1], max(alist, key=itemgetter(1))[1]
(3, 5)
答案 2 :(得分:3)
一种通用的方法是这样的:
alist = [(1,6),(2,5),(2,4),(7,5)]
temp = map(sorted, zip(*alist))
min_x, max_x, min_y, max_y = temp[0][0], temp[0][-1], temp[1][0], temp[1][-1]
对于Python 3,您需要将创建temp
的行更改为:
temp = tuple(map(sorted, zip(*alist)))
这个想法可以被抽象成一个在Python 2和3中都有效的函数:
from __future__ import print_function
try:
from functools import reduce # moved into functools in release 2.6
except ImportError:
pass
# readable version
def minmaxes(seq):
pairs = tuple()
for s in map(sorted, zip(*seq)):
pairs += (s[0], s[-1])
return pairs
# functional version
def minmaxes(seq):
return reduce(tuple.__add__, ((s[0], s[-1]) for s in map(sorted, zip(*seq))))
alist = [(1,6), (2,5), (2,4), (7,5)]
min_x, max_x, min_y, max_y = minmaxes(alist)
print(' '.join(['{},{}']*2).format(*minmaxes(alist))) # 1,7 4,6
triplets = [(1,6,6), (2,5,3), (2,4,9), (7,5,6)]
min_x, max_x, min_y, max_y, min_z, max_z = minmaxes(triplets)
print(' '.join(['{},{}']*3).format(*minmaxes(triplets))) # 1,7 4,6 3,9
答案 3 :(得分:3)
至少使用Python 2.7,“zip”不是必需的,因此这简化为map(max, *data)
(其中data
是元组或相同长度列表的迭代器)。< / p>
答案 4 :(得分:0)
使用枚举和列表理解的另一种解决方案
$ zipinfo IE11.zip
Archive: IE11.zip 5314224734 bytes 1 file
warning [IE11.zip]: 1019257298 extra bytes at beginning or within zipfile
(attempting to process anyway)
error [IE11.zip]: start of central directory not found;
zipfile corrupt.
(please check that you have transferred or created the zipfile in the
appropriate BINARY mode and that you have compiled UnZip properly)
答案 5 :(得分:0)
对于python 3:
alist = [(1,3),(2,5),(2,4),(7,5)]
[x_range, y_range] = list(zip(map(min, *test_list), map(max, *alist)))
print(x_range, y_range) #prints: (1, 7) (3, 5)
由于zip / map返回迭代器<object at 0x00>
,因此您需要使用list()