Home > OS >  Is there a way for finding the name of the variable that was selected by the min function?
Is there a way for finding the name of the variable that was selected by the min function?

Time:10-26

In the Python code below, I am simply assigning OPN_24n4 the minimum value of either Node_23n3 or Node_24n4. However, I also would like to know the name of the variable that was chosen. Is there a concise way of doing this? I suppose I could use some sort of if statement but thought there might be a function I'm unaware of.

OPN_24n4 = min(Node_23n3, Node_23n4)

CodePudding user response:

min, max, and sorted can take a key function, which is a function that manipulate the input in order make the comparison over some part of it or whatever, and we can use this and then make tuples with the name of the variable and its value and with an appropriate key function get the result we desire

>>> min(("var1",10),("var2",2), key=lambda x:x[1])
('var2', 2)
>>> 

CodePudding user response:

If you are working with lists you can get the index of the minimum value with the index method

>>> x = [5,3,7,1,9]
>>> x.index(min(x))
3
>>> 

CodePudding user response:

It seems unlikely that you would ever need a solution like this , and it would probably be relatively fragile but, borrowing from this answer you could create a solution like this using inspect:

import inspect

def named_min(*args):
    min_val = min(args)
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    named_var = [var_name for var_name, var_val in callers_local_vars if var_val is args[args.index(min_val)]][0]
    if args.count(min_val) > 1:
        named_var = 'multiple'
    return min_val, named_var

Node_23n3 = 0
Node_23n4 = 1
OPN_24n4, name = named_min(Node_23n3, Node_23n4)
print(OPN_24n4, name)
Node_23n4 = 0
OPN_24n4, name = named_min(Node_23n3, Node_23n4)
print(OPN_24n4, name)
Node_23n3 = 2
OPN_24n4, name = named_min(Node_23n3, Node_23n4)
print(OPN_24n4, name)
Node_23n5 = -1
OPN_24n4, name = named_min(Node_23n3, Node_23n4, Node_23n5)
print(OPN_24n4, name)

This does do what you're after:

0 Node_23n3
0 multiple
0 Node_23n4
-1 Node_23n5

but I certainly wouldn't recommend it.

  • Related