gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:14 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com