zorange
zorange

Reputation: 71

python3 List with .sort() goes wrong

Im trying to sort a list in Python 3 using Visual Studio Code: I take my list from the arguments in the commandline. The first argument is ignored that's my needle variable. After adding all variables in the lost I want to sort the list. The problem is that it gets sorted in a rather strange way

after 2 comes 21 and then 3 after 5 comes 55 and than 6

This is my commandline:

C:\Users\Gebruikertje\Desktop\Python>python find.py 21 2 3 4 5 6 21 55 3

this is the output:

['2', '21', '3', '3', '4', '5', '55', '6']

This is the part of the code im referring to

import sys

finish = len(sys.argv)
needle = sys.argv[1]
haystack = []
for i in range (2,finish ):
    haystack.append(sys.argv[i])
haystack.sort()
print(haystack)

Upvotes: 3

Views: 134

Answers (3)

bhansa
bhansa

Reputation: 7534

You are trying to sort a list of strings.

Convert them to int while adding them to list.

haystack.append(int(sys.argv[i]))

You can also use map() here:

haystack = map(int, sys.argv[1:])

Upvotes: 2

Eduardo
Eduardo

Reputation: 701

Try:

x = ['2', '21', '3', '3', '4', '5', '55', '6']
y = [int(number) for number in x]
y.sort()

# Result = [2, 3, 3, 4, 5, 6, 21, 55]

Upvotes: 1

Mureinik
Mureinik

Reputation: 312259

The values inputed from argv are strings, and thus are sorted lexicographically. You should convert them to numbers if you wan to sort them numerically. Doing this in a list comprehension could also help clean up some boiler plate from your loop:

haystack = [int(x) for x in sys.argv[1:]]
haystack.sort()

Upvotes: 1

Related Questions