在Python中根据另一个列表找到列表的最大值

huangapple go评论58阅读模式
英文:

Maximum value of a list according to another list in Python

问题

I have two lists res2 and Cb. I want to print maximum value according to an operation as shown below but I am getting an error. I present the expected output.

res2=[3, 4, 6]
Cb=[[0,10,20,30,40,50,60]]

for i in range(0,len(res2)):
    Max=max(Cb[0][res2[i]])
    print(Max)

The error is

in <module>
    Max=max(Cb[0][res2[i]])

TypeError: 'int' object is not iterable

The expected output is

60
英文:

I have two lists res2 and Cb. I want to print maximum value according to an operation as shown below but I am getting an error. I present the expected output.

res2=[3, 4, 6]
Cb=[[0,10,20,30,40,50,60]]

for i in range(0,len(res2)):
    Max=max(Cb[0][res2[i]])
    print(Max)

The error is

in &lt;module&gt;
    Max=max(Cb[0][res2[i]])

TypeError: &#39;int&#39; object is not iterable

The expected output is

60

答案1

得分: 1

IIUC,您想用res2来切片Cb[0],然后获取最大值。

您可以使用:

from operator import itemgetter

res2 = [3, 4, 6]
Cb = [[0, 10, 20, 30, 40, 50, 60]]

out = max(itemgetter(*res2)(Cb[0]))

或者:

out = max(Cb[0][i] for i in res2)

输出:60

英文:

IIUC, you want to slice Cb[0] with res2, then get the max.

You could use:

from operator import itemgetter

res2 = [3, 4, 6]
Cb = [[0,10,20,30,40,50,60]]

out = max(itemgetter(*res2)(Cb[0]))

Or:

out = max(Cb[0][i] for i in res2)

Output: 60

huangapple
  • 本文由 发表于 2023年6月15日 14:13:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定