3

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)
4
  • 1
    you are sorting a list of strings (not integers), try haystack.sort(key = lambda x: int(x)) or just make your list integers to begin with Commented Oct 6, 2017 at 11:49
  • This is because the numbers are strings. Try the same code with integers. Commented Oct 6, 2017 at 11:50
  • @Chris_Rands umm... that could just be key=int... Commented Oct 6, 2017 at 11:53
  • 1
    @JonClements Whoops yep agreed, but they probably actually don't want a list of strings initially Commented Oct 6, 2017 at 11:54

3 Answers 3

2

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:])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot. That was exactly the problem. One step forward in the world of Python
1

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()

Comments

1

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.