How to Get Max() to Return Variable Names Instead of Values in Python

How to get max() to return variable names instead of values in Python?

Make a dictionary and then use max. Also works with min. It will return you the variable name in the form of string.

>>> x = 1
>>> y = 2
>>> z = 3
>>> var = {x:"x",y:"y",z:"z"}
>>> max(var)
3
>>> var.get(max(var))
'z'
>>> var.get(min(var))
'x'
>>>

Get name of variable with highest integer from list Python 3.3.4

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

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

How to get max() to return variable names instead of contents of the variables in R?

We can use which.max to return the index of the first max value and use that to get the names

names(which.max(t))

If there are ties for max value, create a logical vector with ==, get all the position index with which and extract the names

names(which(t == max(t)))

How to find out which variable has the greatest value

You could test each one:

if A > B and A > C and A > D:

or you could just test against the maximum value of the other three:

if A > max(B, C, D):

but it appears what you really want is to figure out which player has the maximum value. You should store your player scores in a dictionary instead:

players = {'A': A, 'B': B, 'C': C, 'D': D}

Now it is much easier to find out who wins:

winner = max(players, key=players.get)
print(winner, 'wins')

This returns the key from players for which the value is the maximum. You could use players throughout your code rather than have separate variables everywhere.

To make it explicit: A > B and C and D won't ever work; boolean logic doesn't work like that; each expression is tested in isolation, so you get A > B must be true, and C must be true and D must be true. Values in Python are considered true if they are not an empty container, and not numeric 0; if these are all integer scores, C and D are true if they are not equal to 0.

How to find the name of a min (or max) attribute?

The magic of vars prevents you from having to make a dictionary up front if you want to have things in instance variables:

class Foo():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c

def min_name(self, names = None):
d = vars(self)
if not names:
names = d.keys()

key_min = min(names, key = (lambda k: d[k]))
return key_min

In action

>>> x = Foo(1,2,3)
>>> x.min_name()
'a'
>>> x.min_name(['b','c'])
'b'
>>> x = Foo(5,1,10)
>>> x.min_name()
'b'

Right now it'll crash if you pass an invalid variable name in the parameter list for min_name, but that's resolvable.

You can also update the dictionary and it's reflected in the source

  def increment_min(self):
key = self.min_name()
vars(self)[key] += 1

Example:

>>> x = Foo(2,3,4)
>>> x.increment_min()
>>> x.a
3


Related Topics



Leave a reply



Submit