JuicyMango17
JuicyMango17

Reputation: 21

List that shows which element has the largest value

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.

Upvotes: 1

Views: 63

Answers (4)

JayJay
JayJay

Reputation: 23

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)
# 'C'

Upvotes: 2

cards
cards

Reputation: 4965

Assuming that each numerical value is positive:

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

index, _ = max(enumerate(lst), key=lambda p: p[1] if isinstance(p[1], float) else 0)
el = lst[index-1]
print(el)

otherwise first filter by type and then get the index of the maximal value

_, index = max(((v, i) for i, v in enumerate(lst) if isinstance(v, float)))
el = lst[index-1]
print(el)

Upvotes: 0

dawg
dawg

Reputation: 103754

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)

Upvotes: 2

Mark
Mark

Reputation: 92440

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')]

Upvotes: 3

Related Questions