Can I sort text by its numeric value in Python?

后端 未结 6 1952
轮回少年
轮回少年 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:02

    For fun & usefulness (for googling ppl, mostly):

    f = lambda i: [int(j) if re.match(r"[0-9]+", j) else j for j in re.findall(r"([0-9]+|[^0-9]+)", i)]
    cmpg = lambda x, y: cmp(f(x), f(y))
    

    use as sorted(list, cmp=cmpg). Additionally, regexes might be pre-compiled (rarely necessary though, actually, with re module's caching). And, it may be (easily) modified, for example, to include negative values (add -? to num regex, probably) and/or to use float values.

    It might be not very efficient, but even with that it's quite useful.

    And, uhm, it can be used as key= for sorted() too.

提交回复
热议问题