How to sort a list of strings numerically?

前端 未结 14 2504
你的背包
你的背包 2020-11-22 03:43

I know that this sounds trivial but I did not realize that the sort() function of Python was weird. I have a list of \"numbers\" that are actually in string for

14条回答
  •  情书的邮戳
    2020-11-22 04:13

    may be not the best python, but for string lists like ['1','1.0','2.0','2', '1.1', '1.10', '1.11', '1.2','7','3','5']with the expected target ['1', '1.0', '1.1', '1.2', '1.10', '1.11', '2', '2.0', '3', '5', '7'] helped me...

    unsortedList = ['1','1.0','2.0','2', '1.1', '1.10', '1.11', '1.2','7','3','5']
    sortedList = []
    sortDict = {}
    sortVal = []
    #set zero correct (integer): examp: 1.000 will be 1 and breaks the order
    zero = "000"
    for i in sorted(unsortedList):
      x = i.split(".")
      if x[0] in sortDict:
        if len(x) > 1:
            sortVal.append(x[1])
        else:
            sortVal.append(zero)
        sortDict[x[0]] = sorted(sortVal, key = int)
      else:
        sortVal = []
        if len(x) > 1:
            sortVal.append(x[1])
        else:
            sortVal.append(zero)
        sortDict[x[0]] = sortVal
    for key in sortDict:
      for val in sortDict[key]:
        if val == zero:
           sortedList.append(str(key))
        else:
           sortedList.append(str(key) + "." + str(val))
    print(sortedList)
    

提交回复
热议问题