Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

string - Can I sort text by its numeric value in 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,
          }

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.

How can I sort the indices correctly?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('.')))

which returns this:

['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.

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)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...