[Introduction to Python] How to sort the contents of a list efficiently with list sort

Reference site: [Introduction to Python] How to sort the contents of a list efficiently with list sort

[Introduction to Python] How to sort the contents of a list efficiently with list sort

When programming, there are occasions when you want to sort the contents of a list. Depending on the language, there is a method of realizing an existing sorting algorithm by making full use of for statements etc., which is surprisingly difficult. However, Python has a function for sorting the list, so it's easy to sort.

This time, I will explain how to sort the contents of the list.

table of contents 1 [Sort using sort function](## Sort using sort function) 2 [Reverse sort using reverse function](## Reverse sort using reverse function) 3 [Sort using sorted function](## Sort using sorted function) 3.1 [Sort in ascending order with sorted function](Sort in ascending order with ### sorted function) 3.2 [Sort in descending order with sorted function](Sort in descending order with ### sorted function) 4 [Sort multidimensional list](## Sort multidimensional list)

Sort using the sort function

The easiest way to list in Python is to use the sort function. The syntax of the sort function is as follows.

list.sort()

Use sort () to sort the contents of the list in ascending order. Character strings are sorted in character code order, and numerical values are sorted in ascending order. If you sort by sort (), the contents of the original list will be replaced.

list1 = ['python', 'list', 'sort']
print('Before sorting:{}'.format(list1))
 
list1.sort()
print('After sorting:{}'.format(list1))

Execution result

Before sorting: [‘python’, ‘list’, ‘sort’] After sorting: ['list', ‘python’, ‘sort’]

Reverse sort using the reverse function

You can easily sort the list using the sort function, but the order is always ascending. If you want to sort in descending order, use the reverse function. The syntax of the reverse function is as follows.

list.reverse()

If you use reverse (), everything in the list will be reversed. Therefore, you can sort the list in descending order by using reverse () after sorting in ascending order using sort ().

list1 = [1,5,3,9,6,7,8]
print('Before sorting:{}'.format(list1))
 
list1.sort()
print('After sorting(ascending order):{}'.format(list1))
 
list1.reverse()
print('After sorting(descending order):{}'.format(list1))

Execution result

Before sorting: [1, 5, 3, 9, 6, 7, 8] After sorting (ascending order): [1, 3, 5, 6, 7, 8, 9] After sorting (descending order): [9, 8, 7, 6, 5, 3, 1]

Sorting using the sorted function

We found that the sort function can be used to sort the list in ascending order, and the reverse function can be used to sort in descending order. However, in the case of sorting using these two functions, the contents of the original list will be rewritten.

If you have sorted but want to restore it, you may want to create a new sorted list without changing the contents if possible. In such a case, the sorted function is convenient.

Sort in ascending order with the sorted function

The sorted function is a function that sorts a list in the same way as the sort function. However, the sorted function returns a sorted list, so unlike the sort function, the contents of the original sort remain the same. The syntax for sorting in ascending order with the sorted function is as follows.

Listing 2= sorted(Listing 1)

Passing List 1 before sorting to sorted returns the sorted list. Substituting it into Listing 2 creates a new Listing 2 that sorts Listing 1. The original list doesn't change, so it's nice to keep the original list in case something goes wrong.

list1 = [1,5,3,9,6,7,8]
list2 = sorted(list1)
 
print('Before sorting:{}'.format(list1))
print('After sorting:{}'.format(list2))

Execution result

Before sorting: [1, 5, 3, 9, 6, 7, 8] After sorting: [1, 3, 5, 6, 7, 8, 9]

Sort in descending order with the sorted function

Sorting with the sorted function results in ascending order, but of course you can also sort in descending order.

Listing 2= sorted(Listing 1)

When using the sorted function, you can sort in descending order by setting the option called reverse to True.

list1 = [1,5,3,9,6,7,8]
list2 = sorted(list1, reverse=True)  #reverse to True

print('Before sorting:{}'.format(list1))
print('After sorting:{}'.format(list2))

Execution result

Before sorting: [1, 5, 3, 9, 6, 7, 8] After sorting: [9, 8, 7, 6, 5, 3, 1] Multidimensional list sorting

So far we have explained how to sort a one-dimensional list, but sometimes you may want to sort a two-dimensional or larger multidimensional list. Multidimensional arrays can be sorted by using sort (), reverse (), sorted () as in 1D.

However, in the case of multidimensional, the result depends on which value is used for sorting. For example, suppose you sort the following list.

list1 = [[1,5,3], [6,4,8], [9,11,2]]

This list1 is a two-dimensional array of three lists with three elements. The sort result of this list1 changes depending on which element of each element list is used as the key.

[[1, 5, 3], [6 ,4 ,8], [9, 11, 2]]  #Key the first element of each list
[[6, 4, 8], [1, 5, 3], [9, 11, 2]]  #Key the second element of each list
[[9, 11, 2], [1, 5, 3], [6, 4, 8]]  #Key the third element of each list

If you sort a multidimensional list normally, it will be sorted using the first element as a key. Use itemgetter to sort by key elements.

from operator import itemgetter

Listing 1.sort(key=itemgetter(1)) #Listing 1は2次元以の配列

itemgetter is a function of the operator library, so you need to import it first. The argument of itemgetter () represents the number of the element you want to key. In the case of itemgetter (1), the list is sorted using the first element as a key.

You can use itemgetter to choose which element to use as a key.

from operator import itemgetter
 
list1 = [[1,5,3], [6,4,8], [9,11,2]]
print('Before sorting:{}'.format(list1))
 
list1.sort(key=itemgetter(0))
print('After sorting(0th element):{}'.format(list1))
 
list1.sort(key=itemgetter(1))
print('After sorting(First element):{}'.format(list1))
 
list1.sort(key=itemgetter(2))
print('After sorting(Second element):{}'.format(list1))

Execution result

Before sorting: [[1, 5, 3], [6, 4, 8], [9, 11, 2]] After sorting (0th element): [[1, 5, 3], [6, 4, 8], [9, 11, 2]] After sorting (first element): [[6, 4, 8], [1, 5, 3], [9, 11, 2]] After sorting (second element): [[9, 11, 2], [1, 5, 3], [6, 4, 8]]

Recommended Posts

[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
How to connect the contents of a list into a string
How to identify the element with the smallest number of characters in a Python list?
[Introduction to Python] How to split a character string with the split function
[Python] A program that rotates the contents of the list to the left
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] How to iterate with the range function?
How to write a list / dictionary type of Python3
How to pass the execution result of a shell command in a list in Python
[python] How to sort by the Nth Mth element of a multidimensional array
[Ubuntu] How to delete the entire contents of a directory
[Python] How to make a list of character strings character by character
How to shuffle a part of a Python list (at random.shuffle)
How to display a list of installable versions with pyenv
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
[Introduction to Python] How to get data with the listdir function
How to check in Python if one of the elements of a list is in another list
How to count the number of occurrences of each element in the list in Python with weight
[Python] How to convert a 2D list to a 1D list
Summary of how to use Python list
How to determine the existence of a selenium element in Python
[python, ruby] fetch the contents of a web page with selenium-webdriver
How to check the memory size of a variable in Python
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
Output the contents of ~ .xlsx in the folder to HTML with Python
I tried to create a list of prime numbers with python
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
How to send a request to the DMM (FANZA) API with python
How to pass the execution result of a shell command in a list in Python (non-blocking version)
How to calculate the volatility of a brand
How to read a CSV file with Python 2/3
[Python] Sort the list of pathlib.Path in natural sort
How to clear tuples in a list (Python)
[Introduction to Python] What is the difference between a list and a tuple?
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Python] Explains how to use the range function with a concrete example
[Introduction to Udemy Python 3 + Application] 19. Copy of list
[Python] How to put any number of standard inputs in a list
Make a copy of the list in Python
I want to sort a list in the order of other lists
How to specify attributes with Mock of python
[Algorithm x Python] How to use the list
Introduction to Python with Atom (on the way)
Receive a list of the results of parallel processing in Python with starmap
A python amateur tries to summarize the list ②
How to format a list of dictionaries (or instances) well in Python
[Introduction to Python] What is the method of repeating with the continue statement?
How to sort by specifying a column in the Python Numpy array.
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
How to access the contents of a Linux disk on a Mac (but read-only)
Python script to get a list of input examples for the AtCoder contest
Note: How to get the last day of the month with python (added the first day of the month)
[Python] How to remove duplicate values from the list
How to convert / restore a string with [] in python
A memo connected to HiveServer2 of EMR with python
Template of python script to read the contents of the file