简体   繁体   English

对 Python 中的字母数值进行排序

[英]sorting alpha numeric values in Python

I have a dictionary entries for the different users like below:我有一个针对不同用户的字典条目,如下所示:

{'usr_1': '111', 'usr_2': '222','usr_22' : '3333', 
 'usr_8': '888','usr_11':'11111','usr_10':'10101'}

I want to sort this dictionary based on the key.我想根据键对这本字典进行排序。 The output should be output 应该是

{'usr_1': '111', 'usr_2': '222','usr_8': '888',
'usr_10':'10101', 'usr_11':'11111','usr_22' : '3333'}

When I tried using the OrderedDict method it just returns changes the list to tuples and doesn't give me the sorted order I wanted.当我尝试使用 OrderedDict 方法时,它只是返回将列表更改为元组,并没有给我想要的排序顺序。

dict1 = {'usr_1': '111', 'usr_2': '222','usr_22' : '3333', 
         'usr_8': '888','usr_11':'11111','usr_10':'10101'}

my_dict = OrderedDict(dict1)
print(my_dict)

Output Output

OrderedDict([('usr_1', '111'), ('usr_2', '222'), ('usr_22', '3333'),
             ('usr_8', '888'), ('usr_11', '11111'), ('usr_10', '10101')])

Can someone help me out?有人可以帮我吗?

In order to sort strings that contain numbers numerically, you can right-justify them to a common maximum length:为了对包含数字的字符串进行排序,您可以将它们右对齐到一个共同的最大长度:

dict(sorted(dict1.items(),key="{0[0]:>20}".format))

output: output:

{'usr_1': '111', 'usr_2': '222', 'usr_8': '888', 'usr_10': '10101', 
 'usr_11': '11111', 'usr_22': '3333'}

Note that this only works if the prefixing character is smaller than "0" (which "_" happens to be).请注意,这仅在前缀字符小于“0”(“_”恰好是)时才有效。 If not, you would need to split the string or convert characters.如果没有,您将需要拆分字符串或转换字符。 (same goes if there are varying length non-digit prefixes) (如果有不同长度的非数字前缀也是如此)

Use a lambda that splits on "_" as key:使用在“_”上拆分的 lambda 作为键:

out = dict(sorted(dct.items(), key=lambda x: int(x[0].split('_')[1])))

Output: Output:

{'usr_1': '111',
 'usr_2': '222',
 'usr_8': '888',
 'usr_10': '10101',
 'usr_11': '11111',
 'usr_22': '3333'}

try尝试

my_dict = OrderedDict(sorted(dict1.items()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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