python - 元组列表中的最小值和最大值
问题描述
我有一个元组列表,我试图获取每个索引处的最小值和最大值。索引 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)
解决方案
要获取每个元素的最小值和最大值,请使用列表推导,如下所示:
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]
推荐阅读
- vue.js - vuetify 2.3+ 表 customSort 单列
- python - Flask-SQLAlchemy:从选定的行中获取值等于某物的列名列表
- javascript - 嵌套对象深度
- node.js - 为什么 .find() 显示快速的 MongoDB 事务时间和缓慢的 node.js 事务时间,而 .findOne() 显示完全相反?
- r - 计算数据框中点组之间的最小距离
- c# - C#在while循环中跳过if语句
- linux - Ubuntu 上的应用切换器中缺少 VSCode 图标
- java - 需要帮助改变模量方程
- javascript - Ramda - allPass 返回真,即使其中一个条件为假
- html - 如何将元素放在封闭标签内