Home > Enterprise >  How to get the name of the variable after it is sorted?
How to get the name of the variable after it is sorted?

Time:09-09

After sorting a list, I need to know the name of the variable the is 1st. How can i do this?

orderA = 3
orderB = 7
orderC = 4
orderD = 2

order = [orderA, orderB, orderC, orderD]
order.sort()
print(order[0])

How can I get the name of the variable for order[0]?

CodePudding user response:

Edit: as others have pointed out, you are not really asking for variable names in the right spirit. What you really want is something more like this

order_dict = {"orderA": 3, "orderB": 7, "orderC": 4, "orderD": 2, "orderE": 3}

sorted_list = [(key, order_dict[key]) for key in sorted(order_dict, key=order_dict.get)]

for tup in sorted_list:
    print(tup[0], end=" ") # orderD orderA orderE orderC orderB

print('') # ignore, for visuals only

for tup in sorted_list:
    print(tup[1], end=" ") # 2 3 3 4 7

print('') # ignore, for visuals only

OP I do not recommend you use the following method, but it still can be achieved, based on this question:

import inspect

def retrieve_name(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]

orderA = 3
orderB = 7
orderC = 4
orderD = 2

order = [orderA, orderB, orderC, orderD]
order.sort()

# Do this if you don't want `var` to be associated with any order variable
for i in range(len(order)):
    print(retrieve_name(order[i]))

# Do this if you don't care
for var in order:
    print(retrieve_name(var)[0])

# output: orderD
#         orderA
#         orderC
#         orderB

CodePudding user response:

Used as reference characters the alphabet via string-module. A custom one can be chosen by replacing background_labels with a string iterable which could be useful if you are dealing with "long" lists of values.

import string

values = 3, 7, 4, 2

prefix = "order"
background_labels = string.ascii_uppercase

ordered_pairs = sorted(zip(background_labels, values), key=lambda p: p[1])
#[('D', 2), ('A', 3), ('C', 4), ('B', 7)]

label, value = ordered_pairs[0]
print(f'{prefix}{label}', value)
#orderD 2
  • Related