**Question:**

How to sort python list string with number inside?

For example, [ "item1", "item13", "item15", "item7" ]

How to write natrual sort order in python?

**Answer:**

There are two basic ways to sort list in python.

**First**, the sorted function. The sorted built-in function returns sorted list. Be careful! The list itself is not sorted. [Line6, Line7]

**Second**, List.sorted() method. The list.sorted() method changes list itself in sorted order.

When list item contains number with string, both sorted function and list.sorted() method does not work properly.

Both line5 and line7 show improper sorted list which is not numeric order.

To figure this out, let's call list.sort() method with lambda function. [Line12]

The list.sort() method allows "key" argument which gives list.sort() method to specify the sorting criteria.

In this example, list elements are consisted with "string" + "number".

**["item7", "item1", "item15", "item13"]**[Line 4]

We want sort these elements in numeric order, like..

**['item1', 'item7', 'item13', 'item15']**[Line 13]

By using built-in sort function, however, sorting process seems not working properly.

**['item1', 'item13', 'item15', 'item7']**[Line 5, 7]

This because 'lexicographic sorting' compares string chracter by character, which means '7' is greater than '1'.

That's why built-in sort function sorts 'item13' is less than 'item7'.

To solve this problem, we need to set the critea to python by passing parameter called "key".

The key of sort function is the number part, not the string.

All elements in this list contain string "item" and numeric value.

By slicing element from 4th index, this can obtain numeric part.

Like element[4:]

In this way, list item with "string" + "number" can be sorted by

**lst.sort(key=lambda x: int(x[4:]))**. [Line 12]
Reference:

Python List.sort() method, Key Functions.

Why do some sorting methods sort by 1, 10, 2, 3 ... ?

## 0 κ°μ λκΈ:

## Post a Comment