gpt4 book ai didi

python - 通过Python查找列表中特定位置的绝对最大值或最小值

转载 作者:行者123 更新时间:2023-12-01 22:03:49 27 4
gpt4 key购买 nike

我有一个数组列表,如下所示:

data = [([-1.01201792,  2.5,  0.68665077]), ([-2.5,  0.5,  2.68189991]), ([-2.5,  3.5, 5.92202221]), ([-2.5, 5.5, 10.19026759]), ([-2.5, 6.5, 15.30091085])]

我试图获取每个数组的绝对最大值,而不考虑数组中的第二个值。例如,在第一个数组中:([-1.01201792, 2.5, 0.68665077]),在不考虑 2.5 的情况下,绝对最大值为 1.01201792。

我希望结果是这样的:

result = [1.01201792, 2.68189991, 5.92202221, 10.19026759, 15.30091085]

我怎样才能实现这个目标?

最佳答案

您应该像编写步骤一样进行编码:

outlist = []                          # create an empty output list
for x in data: # for each sublist in data
val = max(abs(x[0]), abs(x[2])) # find max of absolute of 1st and 3rd
outlist.append(val) # add above value to output list

print(outlist) # print the output list

输出:

[1.01201792, 2.68189991, 5.92202221, 10.19026759, 15.30091085]

如果子列表中可能有超过3个元素,可以使用以下内容:

outlist = []                        # create an empty output list
for x in data: # for each sublist in data
x = [x[0]]+x[2:] # create a new list without 2nd element
val = max(x) # find max of new list
outlist.append(val) # add above value to output list

print(outlist) # print the output list

关于python - 通过Python查找列表中特定位置的绝对最大值或最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62257285/

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