Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting numbers in string format with Python [duplicate]

Tags:

python

sorting

I have a list that has some chapter numbers in string. When I sort the keys using keys function, it gives me wrong results.

keys = ['1.1', '1.2', '2.1', '10.1'] 
keys.sort() 
print keys

['1.1', '1.2', '10.1', '2.1']

How can I use the sort function to get

['1.1', '1.2', '2.1', '10.1']

What if the array has something like this?

['1.1.1', '1.2.1', '10.1', '2.1'] -> ['1.1.1','1.2.1','2.1','10.1']

like image 708
prosseek Avatar asked Apr 08 '10 02:04

prosseek


People also ask

Can you sort a string of numbers in Python?

In Python, you can sort a list with the sort() method or the sorted() function. This article describes how to sort a list of numeric strings not filled with zeros.

How do I sort a list of numbers and strings in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do you sort numeric values in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.


1 Answers

keys.sort(key=lambda x: [int(y) for y in x.split('.')])
like image 199
Ignacio Vazquez-Abrams Avatar answered Oct 22 '22 01:10

Ignacio Vazquez-Abrams