Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

60

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading