Maximum value of a list according to another list in Python
Question:
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
Answers:
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
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
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