开发者

Find the min, max value in a list of tuples

开发者 https://www.devze.com 2023-01-21 20:07 出处:网络
alist = [(1,3),(2,5),(2,4),(7,5)] 开发者_开发知识库 I need to get the min max value for each position in tuple.
alist = [(1,3),(2,5),(2,4),(7,5)]
开发者_开发知识库

I need to get the min max value for each position in tuple.

Fox example: The exepected output of alist is

min_x = 1
max_x = 7

min_y = 3
max_y = 5

Is there any easy way to do?


map(max, zip(*alist))

This first unzips your list, then finds the max for each tuple position

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

This will also work for tuples of any length in a list.


>>> 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)


The zip is not necessary, so this simplifies to map(max, *data) (where data is an iterator over tuples or lists of the same length).


A generalized approach would be something like this:

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]

For Python 3, you'd need change the line that createstempto:

temp = tuple(map(sorted, zip(*alist)))

The idea can be abstracted into a function which works in both Python 2 and 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


Another solution using enumerate and list comprehension

alist = [(1,3),(2,5),(2,4),(7,5)]

for num, k in enumerate(['X', 'Y']):
    print 'max_%s' %k, max([i[num] for i in alist])
    print 'min_%s' %k, min([i[num] for i in alist])


For 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)

Since zip/map returns an iterator <object at 0x00> you need to use list()

0

精彩评论

暂无评论...
验证码 换一张
取 消