首页 > 解决方案 > 按列表列表中的索引计算最小值或最大值

问题描述

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并执行上面解释的步骤.

标签: pythonpython-3.xlistdictionary

解决方案


这是您可以通过调度程序字典和几个列表推导来构建逻辑的一种方式:

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或。maxfuncs
  • map(itemgetter(i), L)i返回对内每个列表的第 th 个元素的迭代器L
  • 在此迭代器上应用funcs[i%2]会返回最小值或最大值。

推荐阅读