John
John

Reputation: 29

Unable to convert arguments

I want to sort the numbers in a list based on the last digit.

Here is my code:

import sys
list1 = sys.argv[1]
list1_split = list1.split(",")

sorted_numbers = sorted(list1_split, key=lambda x: x%10)
print("Sorted numbers are: ", sorted_numbers)

This is what I get on the command prompt:

C:\Users\john\pythonprojects\test1> testing.py 45,60,51,24,62,49
Traceback (most recent call last):
  File "C:\Users\john\pythonprojects\test1\testing.py", line 6, in <module>
    sorted_numbers = sorted(list1_split, key=lambda x: x % 10)
  File "C:\Users\john\pythonprojects\test1\testing.py", line 6, in <lambda>
    sorted_numbers = sorted(list1_split, key=lambda x: x % 10)
TypeError: not all arguments converted during string formatting

The expected output should be: [60, 51, 62, 24, 45, 49]

I can't figure out how to solve this error

Upvotes: 1

Views: 597

Answers (4)

Sudheer
Sudheer

Reputation: 33

The argument you are taking from command line will be stored as string. So all the elements in the list1_split list are strings. You cannot perform modulo on them. You can just convert the elements into integer format in the lambda key itself.

like here sorted_numbers = sorted(list1_split, key=lambda x: int(x)%10)

Im getting this output.

enter image description here

Edit: Note that the output is a list of strings. As we have not explicitly converted them to integers.

Upvotes: 0

GZ0
GZ0

Reputation: 4268

If the input numbers are guaranteed to be non-negative, the numeric computation x % 10 is equivalent to a string operation x[-1]. Besides converting all strings to numbers, you can also change the lambda function to lambda x: x[-1] to make the program work.

Upvotes: 0

Vinsensius Indra
Vinsensius Indra

Reputation: 11

You're mixing different format there.

Split method resulting list of strings. If you want to perform modulo operation, typecasting the string into integer would work.

sorted_numbers = sorted(list1_split, key=lambda x: int(x)%10)

Upvotes: 1

Alexandru Dinu
Alexandru Dinu

Reputation: 1267

list1_split is a list of strings - you need to make them ints. A straightforward way of doing this is to use map.

sorted_numbers = sorted(map(int, list1.split(",")), key=lambda x: x % 10)

Upvotes: 3

Related Questions