在python中排序字母数字字典键 [英] Sorting alphanumerical dictionary keys in python

查看:199
本文介绍了在python中排序字母数字字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典的A1-A15,B1-B15等。运行dictionary.keys()。sort()结果在A1,A10,A11 ...


$ b $
key.source()
key.sort()
返回map(dictionary.get,键)

我如何排序,以便它们按正确的顺序进行排序,即A1,A2, A3 ...?

解决方案

  keys.sort(key = lambda k: [0],int(k [1:])))

编辑:键不像A23,例如AA12将停止该程序。在一般情况下,请参阅 natsort函数的Python模拟(使用自然顺序算法排序列表)


I have a dictionary of keys like A1-A15, B1-B15 etc. Running dictionary.keys().sort() results in A1, A10, A11 ...

def sort_keys(dictionary):
    keys = dictionary.keys()
    keys.sort()
    return map(dictionary.get, keys)

How do I sort it so that they get in the right order, ie A1, A2, A3 ... ?

解决方案

keys.sort(key=lambda k:(k[0], int(k[1:])) )

Edit: This will fail in the keys are not like A23, e.g. AA12 will stop the program. In the general case, see Python analog of natsort function (sort a list using a "natural order" algorithm).

这篇关于在python中排序字母数字字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆