简体   繁体   中英

return the name of a sorted value in Python 3

I have values like

amity = 0
erudite = 2

etc.

And I am able to sort the integers with

 print (sorted([amity, abnegation, candor, erudite, dauntless]))`

but I want the variable names to be attached to the integers as well, so that when the numbers are sorted I can tell what each number means. Is there a way to do this?

Define a mapping between the names and the numbers:

numbers = dict(dauntless=42, amity=0, abnegation=1, candor=4, erudite=2)

Then sort :

d = sorted(numbers.items(), key=lambda x: x[1])
print(d)
# [('amity', 0), ('abnegation', 1), ('erudite', 2), ('candor', 4), ('dauntless', 42)]

To keep the result as a mapping/dictionary, call collections.OrderedDict on the sorted list:

from collections import OrderedDict

print(OrderedDict(d))
# OrderedDict([('amity', 0), ('abnegation', 1), ('erudite', 2), ('candor', 4), ('dauntless', 42)])

Python has a built in data-type called dictionary , it is used to map key, value pairs. It is pretty much what you asked for in your question, to attach a value into a specific key .

You can read a bit more about dictionaries here .

What I think you should do is to create a dictionary and map the names of the variables as strings to each of their integer values as shown below:

amity = 0
erudite = 2
abnegation = 50
dauntless = 10
lista = [amity, erudite, abnegation, dauntless]
dictonary = {} # initialize dictionary
dictionary[amity] = 'amity'# You're mapping the value 0 to the string amity, not the variable amity in this case.
dictionary[abnegation] = 'abnegation'
dictionary[erudite] = 'erudite'
dictionary[dauntless] = 'dauntless'
print(dictionary) # prints all key, value pairs in the dictionary
print(dictionary[0]) # outputs amity.
for item in sorted(lista):
    print(dictionary[x]) # prints values of dictionary in an ordered manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM