简体   繁体   中英

sort method returning incorrect output

So I was trying to sort a list of numbers but when I enter a list of numbers such as 48 35 32 5 5 16 5 16 28 29. It won't sort as intended.

My code:

def calculate():
    nums = input("Enter a number list: ")
    numsList = nums.split()
    sortedNums = sorted(numsList)
    print(sortedNums)

calculate()

So if I enter a list like this 48 35 32 5 5 16 5 16 28 29. It will return

['16', '16', '28', '29', '32', '35', '48', '5', '5', '5']

instead of

['5', '5', '5', '16', '16', '28', '29', '32', '35', '48']

Does anyone know how to fix this?

You are sorting strings rather than numbers, so you get them in lexicographical order, if only integers are allowed simply change

sortedNums = sorted(numsList)

to

sortedNums = sorted(numsList, key=int)

If floats are allowed use float instead of int .

In python sorted() will return a sorted list, but not in the way you expected. It will sort the values based on ASCII code. You can see that the sort happens forfirst code in each number and if they are equal, it goes to next code.

You should be able to define your own:

import numpy as np
def selection_sort(x):
for i in range(len(x)):
    swap = i + np.argmin(x[i:])
    (x[i], x[swap]) = (x[swap], x[i])
return x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM