jpcgandre
jpcgandre

Reputation: 1505

Get name of variable corresponding to maximum value in a list

I have this code:

timeLS1 = 0.1
timeLS2 = 0.2
timeLS3 = 0.15
timeLS4 = 0.5
timeLS5 = 0.4
timeLS6 = 0.3
timeLSv = (timeLS1, timeLS2, timeLS3, timeLS4, timeLS5, timeLS6)
timeLS = max(timeLSv)
print timeLS
index_max = timeLSv.index(timeLS)
print index_max

I'd like to get the maximum (timeLS) plus the name of the variable (timeLS1, ...., timeLS6) that corresponds to the maximum.

What's the easiest way to do this (instead of doing if loops after getting index_max)?

Thanks

Upvotes: 2

Views: 1186

Answers (1)

alecxe
alecxe

Reputation: 473833

Not sure if it's the best approach, but looks good:

timeLS1 = 0.1
timeLS2 = 0.2
timeLS3 = 0.15
timeLS4 = 0.5
timeLS5 = 0.4
timeLS6 = 0.3

data = {key: value for key, value in locals().iteritems() if 'timeLS' in key}

key, value = max(data.iteritems(), key=lambda x: x[1])
print key, value  # prints 'timeLS4 0.5'

You might want to avoid to create additional data dictionary also.

Hope that helps.

Upvotes: 2

Related Questions