Python .sort() not working as expected

前端 未结 8 881
南笙
南笙 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:22

    The comparator operator is treating your input as strings instead of integers. In string comparsion 2 as the 3rd letter is lexically greater than 1. reversed = str(mult)[::-1]

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

    No need to convert to int. mult already is an int and as you have checked it is a palindrome it will look the same as reversed, so just:

    list.append(mult)
    
    0 讨论(0)
  • 2020-12-03 22:33

    You're sorting strings, not numbers. Strings compare left-to-right.

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

    Your list contains strings so it is sorting them alphabetically - try converting the list to integers and then do the sort.

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

    You are sorting strings, not numbers. '101101' < '10201' because '1' < '2'. Change list.append(reversed) to list.append(int(reversed)) and it will work (or use a different sorting function).

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

    No, it is sorting properly, just that it is sorting lexographically and you want numeric sorting... so remove the "str()"

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