0

I have a list of numbers and I want to find the var with the highest value but I don't want to use max() because I want the program to return the variables name with the highest value, not the value. Example code:

var1=0
var2=1
var3=2
list[var1,var2,var3]
  • You're almost certainly better off using a list instead of individual variables. If you need to associate each value with a key such as a string, use a dict. Then you can use the built-in `max` to find the biggest member, etc. – tripleee Sep 17 '22 at 10:56
  • Possible duplicate of https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – tripleee Sep 17 '22 at 10:58

2 Answers2

0

This is a strange requirement to the variable name :), You can use globals for this.

In [1]: var1=0
   ...: var2=1
   ...: var3=2

In [2]: d = {k:i for k,i in globals().items() if isinstance(i, int)}

In [3]: d
Out[3]: {'var1': 0, 'var2': 1, 'var3': 2}

In [4]: max(d, key=d.get)
Out[4]: 'var3'
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
0
var1=0
var2=1
var3=2
l = [var1,var2,var3]
max_val = l.index(max(l))
my_var_name = [ k for k,v in globals().items() if v == l[max_val]]
my_var_name
Will
  • 1,619
  • 5
  • 23