python - 按列表列表中的索引计算最小值或最大值
问题描述
list_of_elements = [1255, 1256, 1257, 1258, 1259]
print(components[1255],components[1256],components[1257],components[1258],components[1259])
打印输出为:
[481, 498, 5142, 5157] [481, 497, 5192, 5199] [481, 498, 5219, 5238] [481, 484, 5239, 5242] [481, 487, 5269, 5271)]
我想要做的是取第一个索引(0)的最小数字,第二个最大的,第三个最小的和第四个最大的,所以在这种情况下我最终会得到:
[481,498,5142,5271]
所以,再一次,基本上我会得到一个元素列表(在这种情况下,它list_of_elements
可能有 0 值直到未知),然后我必须输入该列表的元素作为字典中的键components
并执行上面解释的步骤.
解决方案
这是您可以通过调度程序字典和几个列表推导来构建逻辑的一种方式:
list_of_elements = [1255, 1256, 1257, 1258, 1259]
# extract data via list comprehension
L = [components[i] for i in list_of_elements]
# defined explicitly for demonstration
L = [[481, 498, 5142, 5157], [481, 497, 5192, 5199],
[481, 498, 5219, 5238], [481, 484, 5239, 5242],
[481, 487, 5269, 5271]]
from operator import itemgetter
# define dispatcher dictionary
funcs = {0: min, 1: max}
# apply via list comprehension
res = [funcs[i%2](map(itemgetter(i), L)) for i in range(len(L[0]))]
print(res)
[481, 498, 5142, 5271]
解释
i%2
根据您的索引是偶数还是奇数,返回 0 或 1。funcs[i%2]
返回字典中定义的min
或。max
funcs
map(itemgetter(i), L)
i
返回对内每个列表的第 th 个元素的迭代器L
。- 在此迭代器上应用
funcs[i%2]
会返回最小值或最大值。
推荐阅读
- r - 在具有可变数量分隔符的列上使用 tidyr::separate
- jmeter - 负载测试 - Jmeter PreProcessor
- php - Symfony 注册新用户 getUser 在处理请求时返回 null
- machine-learning - 如何在姿势估计中找到不正确的运动
- django - 登录后如何使用 LoginRequiredMixin 让 Django 重定向到请求的页面?
- python - 今天开始使用Python,遇到了一个无法真正解决的问题
- go - Golang:在单个选择中使用多个代码案例阻止整个循环
- python - Python将动态值设置为字典
- c# - 如何获取通过 Azure 函数事件中心触发器接收到的事件的 messageId 或 eventId?
- oracle - ADF_FACES-60097