Python .sort() not working as expected

前端 未结 8 882
南笙
南笙 2020-12-03 22:06

Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren\'t quite what I expect. The program iterates throug

相关标签:
8条回答
  • 2020-12-03 22:45

    You have your numbers stored as strings, so python is sorting them accordingly. So: '101x' comes before '102x' (the same way that 'abcd' will come before 'az').

    0 讨论(0)
  • 2020-12-03 22:48

    Sort is doing its job. If you intended to store integers in the list, take Lukáš advice. You can also tell sort how to sort, for example by making ints:

    list.sort(key=int)
    

    the key parameter takes a function that calculates an item to take the list object's place in all comparisons. An integer will compare numerically as you expect.

    (By the way, list is a really bad variable name, as you override the builtin list() type!)

    0 讨论(0)
提交回复
热议问题