我可以在Python中按文本的数值对其进行排序吗? [英] Can I sort text by its numeric value in Python?
问题描述
我在Python中使用以下形式的键来表示字典:
I have dict in Python with keys of the following form:
mydict = {'0' : 10,
'1' : 23,
'2.0' : 321,
'2.1' : 3231,
'3' : 3,
'4.0.0' : 1,
'4.0.1' : 10,
'5' : 11,
# ... etc
'10' : 32,
'11.0' : 3,
'11.1' : 243,
'12.0' : 3,
'12.1.0': 1,
'12.1.1': 2,
}
有些索引没有子值,有些索引有一个子级别,有些索引有两个.如果我只有一个子级别,则可以将它们全部视为数字并按数字排序.第二个子级别迫使我将它们全部当作字符串来处理.但是,如果我像字符串一样对它们进行排序,则在1
之后将10
在2
之后具有20
.
Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I'll have 10
following 1
and 20
following 2
.
如何正确排序索引?
注意:我真正想做的是打印出按索引排序的字典.如果有比通过某种方式对它进行排序更好的方法,那对我来说很好.
Note: What I really want to do is print out the dict sorted by index. If there's a better way to do it than sorting it somehow that's fine with me.
推荐答案
您可以按所需的方式对键进行排序,方法是将其拆分为'.然后将每个组件转换为整数,如下所示:
You can sort the keys the way that you want, by splitting them on '.' and then converting each of the components into an integer, like this:
sorted(mydict.keys(), key=lambda a:map(int,a.split('.')))
返回以下内容:
['0',
'1',
'2.0',
'2.1',
'3',
'4.0.0',
'4.0.1',
'5',
'10',
'11.0',
'11.1',
'12.0',
'12.1.0',
'12.1.1']
您可以遍历该键列表,并根据需要将值从字典中拉出.
You can iterate over that list of keys, and pull the values out of your dictionary as needed.
您还可以非常相似地对mydict.items()的结果进行排序:
You could also sort the result of mydict.items(), very similarly:
sorted(mydict.items(), key=lambda a:map(int,a[0].split('.')))
这为您提供了(键,值)对的排序列表,如下所示:
This gives you a sorted list of (key, value) pairs, like this:
[('0', 10),
('1', 23),
('2.0', 321),
('2.1', 3231),
('3', 3),
# ...
('12.1.1', 2)]
这篇关于我可以在Python中按文本的数值对其进行排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!