首页 > 解决方案 > 元组列表中的最小值和最大值

问题描述

我有一个元组列表,我试图获取每个索引处的最小值和最大值。索引 1 似乎工作正常。但是,对于索引 2,我期望值为 (-2,11),但我得到的是 (5, 5)。谁能解释一下出了什么问题?谢谢你。

test_list = [(-2, 5), (-1, 5), (0, 6), (0, 7), (0, 7), (1, 8), (2, 9), (2, 9), (3, 10),
(4, 11), (-1, 4), (0, 5), (0, 5), (0, 6), (1, 7), (2, 7), (2, 8), (3, 9), (4, 9), (5, 10),
(0, 3), (0, 4), (0, 5), (1, 5), (2, 6), (2, 7), (3, 7), (4, 8), (5, 9), (5, 9), (0, 2),
(0, 3), (1, 4), (2, 5), (2, 5), (3, 6), (4, 7), (5, 7), (5, 8), (6, 9), (0, 2), (1, 2),
(2, 3), (2, 4), (3, 5), (4, 5), (5, 6), (5, 7), (6, 7), (7, 8), (1, 1), (2, 2), (2, 2),
(3, 3), (4, 4), (5, 5), (5, 5), (6, 6), (7, 7), (7, 7), (2, 0), (2, 1), (3, 2), (4, 2),
(5, 3), (5, 4), (6, 5), (7, 5), (7, 6), (8, 7), (2, 0), (3, 0), (4, 1), (5, 2), (5, 2),
(6, 3), (7, 4), (7, 5), (8, 5), (9, 6), (3, 0), (4, 0), (5, 0), (5, 1), (6, 2), (7, 2),
(7, 3), (8, 4), (9, 5), (9, 5), (4, -1), (5, 0), (5, 0), (6, 0), (7, 1), (7, 2), (8, 2),
(9, 3), (9, 4), (10, 5)]

res1 = max(test_list)[0],min(test_list)[0]  
res2 = max(test_list)[1],min(test_list)[1]

print ("The min of index 1 :  " +  str(res1))
print ("The min of index 2 :  " +  str(res2))
#The min of index 1 :  (10, -2)
#The min of index 2 :  (5, 5)

标签: pythonlisttuplesmaxmin

解决方案


要获取每个元素的最小值和最大值,请使用列表推导,如下所示:

test_list_min = [min(y[x] for y in test_list) for x in range(len(test_list[0]))]
test_list_max = [max(y[x] for y in test_list) for x in range(len(test_list[0]))]

print(test_list_min)
# [-2, -1]

print(test_list_max)
# [10, 11]

推荐阅读