Get the variable name with the highest number from a Python 3.3.4 list

Recently tried something similar to PHP to get the largest number of 3 variables

(Of course, in Python form) However, when I return the value, I get the value of the variable, not the name of the variable.

My array looks like this:

x = 1

y = 2

z = 3

alloutputs = [x, y, z]

The farthest and ugliest before you need help:

alloutputs[alloutputs.index(max(alloutputs))]

However, it still gives me an integer value of the highest value! How can I return the name x, y or z depending on which is the largest?

+4
source share
5 answers

As @zhangxaochen says, you need to use a dictionary or named tuple. You can use a dictionary like this:

>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> max(d, key=d.get)
'z'
+9
source

. namedtuple:

In [296]: d=dict(x=1, y=2, z=3)

In [297]: from operator import itemgetter
     ...: max(d.items(), key=itemgetter(1))[0]
     ...: 
Out[297]: 'z'
+2
x, y, z = 1, 2, 3
alloutputs = ["x", "y", "z"]
print max(alloutputs, key = locals().get)

However, if you really need to do this, you can reconsider your design, IMHO.

+1
source

Disclaimer: This is terrible and you should not do this.

[var for var in dir() if eval(var) == max(all)][0]

It does what you want, but as others have said, it will be much better for you to use the dictionary.

+1
source

You can use the dictionary:

alloutputs = {'x':1,'y':2,'z':3}
maxvalue = max(alloutputs.values())
print [k for k, v in alloutputs.iteritems() if v == maxvalue]
0
source

Source: https://habr.com/ru/post/1527525/


All Articles