Python .sort() not working as expected

前端 未结 8 934
南笙
南笙 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: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!)

提交回复
热议问题