python - 通过列表列表中的索引计算最小值或最大值

标签 python python-3.x list dictionary

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 到未知的值),然后我必须输入该列表的元素作为字典组件中的键并执行上面解释的步骤。

最佳答案

这是通过调度程序字典和几个列表理解来构建逻辑的一种方法:

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]返回 minmaxfuncs 中所定义字典。
  • map(itemgetter(i), L)返回 i 上的迭代器L 内每个列表的第一个元素.
  • 正在申请 funcs[i%2]此迭代器返回最小值或最大值。

关于python - 通过列表列表中的索引计算最小值或最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51079753/

相关文章:

python - 在python列表中将数字转换为成绩

python - 高级自定义排序

python - 使用 numpy 广播减去二维数组

python - 检查向量的准确性

python - python 库中的 "non-integer arg 1 for randrange()"

python-3.x - Python : How to turn an IMAGE into a STRING and back?

Python缓存列表

python - 对列表列表进行排序的方法?

python - 删除元素,然后迭代并组合列表中的元素python

python - 内置双星号电源功能未按预期工作