简体   繁体   English

如何使用 Python 按字母数字顺序按值对字典进行排序?

[英]How can I sort a dictionary by value in alphanumeric order with Python?

Im having a problem while sorting my dictionary with alphanumeric values.我在用字母数字值对字典进行排序时遇到问题。 Each value has at least one letter in front (sometimes two) followed by some numbers.每个值的前面至少有一个字母(有时是两个),后跟一些数字。 Example:例子:

shoppingList = {'milk': 'W30', 'eggs': 'W29', 'tuna': 'W3', 'gum': 'CL24', 'beans': 'W6'}

When Im sorting it:当我对它进行排序时:

sorted_dict = sorted(shoppingList.items(), key = operator.itemgetter(1))

for i in sorted_dict:
    print(i)

Output:输出:

('gum', 'CL24')
('eggs', 'W29')
('tuna', 'W3')
('milk', 'W30')
('beans', 'W6')

So it seems the sort is only using the first number it comes across.所以看起来排序只使用它遇到的第一个数字。 Is there a way to get the output as有没有办法得到输出

('gum', 'CL24')
('tuna', 'W3')
('beans', 'W6')
('eggs', 'W29')
('milk', 'W30')

Thank you in advance.先感谢您。

Its sorting strings, not numbers, you need to parse the integer.它的排序字符串,而不是数字,你需要解析整数。

The one line approach would be ugly, so i'd be tempted to convert the given key below into a seperate function that can handle the splitting of the list单行方法会很丑,所以我很想将下面给定的键转换为一个单独的函数,可以处理列表的拆分

sorted(
    shoppingList.items(),
    key=lambda k: (
        ''.join(x for x in k[1] if not x.isdigit()),
        int(''.join(x for x in k[1] if x.isdigit())) 
    )
)
 [('gum', 'CL24'), ('tuna', 'W3'), ('beans', 'W6'), ('eggs', 'W29'), ('milk', 'W30')]

The module natsort will do this in the order you want.模块natsort将按照您想要的顺序执行此操作。

from natsort import natsorted
from operator import itemgetter

D = natsorted(shoppingList.items(), key=itemgetter(1))

[('gum', 'CL24'), ('tuna', 'W3'), ('beans', 'W6'), ('eggs', 'W29'), ('milk', 'W30')]

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

相关问题 我如何按时间降序对python字典进行排序 - How can i sort python dictionary by time in descending order 如何根据 python 中的值大小对字典进行排序? - How can I order dictionary according to value size in python? 如何在 python 中将嵌套列表作为字典值进行迭代和排序? - How can i iterate and order nested list as a dictionary value in python? 如何按字典值对字典排序? - How can I sort the dictionary by its value? python-如何按降序对值排序? - How to sort by value in descending order an Ordered Dictionary in python? 如何在python中按原样(以dict格式排序)按值对字典进行排序? - How can I sort a dictionary by value as-is (sort in a dict format) in python? Python 按值按降序对字典进行排序,然后按升序对子组进行排序? - Python sort dictionary by value in descending order then sort subgroups in ascending order? 在Python中,我如何自然地对字母数字字符串列表进行排序,以使字母字符排在数字字符之前? - In Python, how can I naturally sort a list of alphanumeric strings such that alpha characters sort ahead of numeric characters? 如何在字母顺序排序python中的字母数字字符串? - how to sort alphanumeric string in python with alphabetical order comes first? 如何使用Python获取字母数字列表中的最高值? - How can I grab the highest value in alphanumeric list using Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM