在python3中返回排序值的名称

2024-09-29 23:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的价值观

amity = 0
erudite = 2

等等

我可以用

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

但是我希望变量名也附加到整数上,这样当对数字进行排序时,我就可以知道每个数字的含义。 有办法吗?你知道吗


Tags: 排序数字整数sortedprint含义价值观办法
2条回答

Python有一个名为dictionary的内置数据类型,用于映射键、值对。这正是你在问题中所要求的,把一个value附加到一个特定的key。你知道吗

你可以多读一些关于词典的内容。你知道吗

我认为您应该创建一个字典,并将变量名作为字符串映射到它们的每个整数值,如下所示:

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.

定义名称和数字之间的映射:

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

然后排序:

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

要将结果保留为映射/字典,请调用排序列表上的^{}

from collections import OrderedDict

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

相关问题 更多 >

    热门问题