Home > database >  List that shows which element has the largest value
List that shows which element has the largest value

Time:10-21

I am trying to make a function that will take elements and values input by the user, and list whichever element has the highest value. For example,

['H', 14.5, 'Be', 2.5, 'C', 50.5, 'O', 22.5 'Mg', 4.0, 'Si', 6.0]

the correct answer is 'C'. I can't seem to figure out how to get this to work. I don't have any code yet, unfortunately.

CodePudding user response:

You can zip the list with itself to get alternating tuples. If you put the number first, you can just use max() to get the largest. This assumes there are not ties:

l = ['H', 14.5, 'Be', 2.5, 'C', 50.5, 'O', 22.5, 'Mg', 4.0, 'Si', 6.0]
num, symbol = max(zip(l[1::2], l[::2]))
# (50.5, 'C')

This works because tuples are compared in order and zipping alternating values gives a collection of tuples like:

list(zip(l[1::2], l[::2]))
# [(14.5, 'H'), (2.5, 'Be'), (50.5, 'C'), (22.5, 'O'), (4.0, 'Mg'), (6.0, 'Si')]

CodePudding user response:

Given:

li=['H', 14.5, 'Be', 2.5, 'C', 50.5, 'O', 22.5, 'Mg', 4.0, 'Si', 6.0]

Create tuples and then take max of those tuples:

>>> max(((li[i],li[i 1]) for i in range(0,len(li),2)), key=lambda t: t[1])
('C', 50.5)

CodePudding user response:

Welcome to StackOverflow! As far as I understand your question, you try to find a maximum element in a list that contains both strings (e.g., 'C') as keys and numbers (e.g., '50.5') as values. For this purpose, a dictionary is more convenient:

dictionary = {'H': 14.5, 'Be': 2.5, 'C': 50.5, 'O': 22.5, 'Mg': 4.0, 'Si': 6.0}
max_key = max(dictionary, key=dictionary.get)
print(max_key)

I hope it helps.

  • Related