Can I sort text by its numeric value in Python?

后端 未结 6 1941
轮回少年
轮回少年 2020-12-16 01:26

I have dict in Python with keys of the following form:

mydict = {\'0\'     : 10,
          \'1\'     : 23,
          \'2.0\'   : 321,
          \'2.1\'   : 3         


        
6条回答
  •  伪装坚强ぢ
    2020-12-16 02:14

    Python's sorting functions can take a custom compare function, so you just need to define a function that compares keys the way you like:

    def version_cmp(a, b):
      '''These keys just look like version numbers to me....'''
      ai = map(int, a.split('.'))
      bi = map(int, b.split('.'))
      return cmp(ai, bi)
    
    for k in sorted(mydict.keys(), version_cmp):
      print k, mydict[k]
    

    In this case you should better to use the key parameter to sorted(), though. See Ian Clelland's answer for an example for that.

提交回复
热议问题