英文:
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 <module>
Max=max(Cb[0][res2[i]])
TypeError: 'int' 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论