Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (12.7k points)

I realize that this sounds paltry however I didn't understand that the sort() function of Python was abnormal. I have a rundown/list of "numbers" that are really in string structure, so I first proselyte/convert them to ints, at that point endeavor a sort. 

list1=["1","10","3","22","23","4","2","200"]

for item in list1:

    item=int(item)

list1.sort()

print list1

Gives me:

['1', '10', '2', '200', '22', '23', '3', '4']

But, What I want is:

['1','2','3','4','10','22','23','200']

I've searched for a portion of the algorithms related to arranging numeric sets, however the ones I discovered all include arranging alphanumeric sets.

I realize this is likely an easy decision issue however google and my coursebook doesn't offer much else or less valuable than the .sort() function.

1 Answer

0 votes
by (26.4k points)

You haven't really changed your strings over to ints. Or then again rather, you did, yet then you didn't do anything with the outcomes. What you need is:

list1 = ["1","10","3","22","23","4","2","200"]

list1 = [int(x) for x in list1]

list1.sort()

In the event that for reasons unknown you need to keep strings rather than ints (typically an impractical notion, yet perhaps you need to save driving zeros or something), you can utilize a key function. sort takes a named boundary/parameter, key, which is a capacity/function that is approached every component before it is analyzed. The key capacity's return esteems are looked at as opposed to contrasting the rundown components straightforwardly:

list1 = ["1","10","3","22","23","4","2","200"]

# call int(x) on each element before comparing it

list1.sort(key=int)

Want to become an expert in Python? Join the python course fast!

Related questions

0 votes
1 answer
asked Aug 1, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
2 answers
asked Jul 22, 2019 in Python by Sammy (47.6k points)

Browse Categories

...