When you want to sort a multidimensional list by multiple lines

One-dimensional time

import random
a = [random.randint(-5, 5) for _ in range(10)]
a.sort()
print('sorted: {}'.format(a))

>>      [4, -3, 0, -2, 1, 4, -1, -3, 2, 3]
sorted: [-3, -3, -2, -1, 0, 1, 2, 3, 4, 4]

As expected, they are arranged in ascending order. Similarly for strings

#Make an appropriate str type list
s = [chr(random.randint(97, 97+25)) for i in range(10)]
print(s)
s.sort()
print('sorted: {}'.format(s))
>>      ['v', 'm', 'h', 'n', 'o', 'i', 'w', 'o', 'q', 'r']
sorted: ['h', 'i', 'm', 'n', 'o', 'o', 'q', 'r', 'v', 'w']

When multidimensional

Consider a list like this as an example. (* From the test case of ABC128-B)

a = [['khabarovsk', 20],
     ['moscow', 10],
     ['kazan', 50],
     ['kazan', 35],
     ['moscow', 60],
     ['khabarovsk', 40]]

Suppose you want to sort the first row of this array, and if the elements of the first row are the same, sort the numbers in the second row in ascending order.

Method 1: Play with the sorted argument key

By specifying the key as shown below, the specified lines will be sorted in order.

print(sorted(a, key=lambda x:(x[0], x[1])))
>>
[['kazan', 35], 
 ['kazan', 50], 
 ['khabarovsk', 20], 
 ['khabarovsk', 40], 
 ['moscow', 10], 
 ['moscow', 60]]

#If you specify in the reverse order
print(sorted(a, key=lambda x:(x[1], x[0])))
>>
[['moscow', 10],
 ['khabarovsk', 20],
 ['kazan', 35],
 ['khabarovsk', 40],
 ['kazan', 50],
 ['moscow', 60]]

#In the case of numerical value-You can sort in descending order by adding.
print(sorted(a, key=lambda x:(x[0], -x[1])))
>>
[['kazan', 50],
 ['kazan', 35],
 ['khabarovsk', 40],
 ['khabarovsk', 20],
 ['moscow', 60],
 ['moscow', 10]]

Method 2: Just sort () is enough

First, try using sort () on a multidimensional list.

b = [[chr(random.randint(97, 97+25)), random.randint(-5, 5)] for i in range(5)]
print(b)
b.sort
print('sorted: {}'.format(b))
>>
        [['r', 1], ['a', 0], ['k', -2], ['z', -2], ['g', -3]]
sorted: [['a', 0], ['g', -3], ['k', -2], ['r', 1], ['z', -2]]

As you can see, the basics are sorted only along the first row.

Now, let's use sort () in the case like the example.

a.sort()
print(a)
>>
[['kazan', 35],
 ['kazan', 50],
 ['khabarovsk', 20],
 ['khabarovsk', 40],
 ['moscow', 10],
 ['moscow', 60]]

that? ?? I got the same result as when I specified the keys of method 1 in order. The python sort function is ** sorted by the basic first row, but it seems that the elements of the first row are sorted by comparing the next second row for the same column **. So if you wanted to do something like the example, you could just use sort ().

If you devise it, you can do it in descending order of numerical values.

for i in a:
  i[1] = -i[1]
a.sort()
print(a)
>>
[['kazan', -50],
 ['kazan', -35],
 ['khabarovsk', -40],
 ['khabarovsk', -20],
 ['moscow', -60],
 ['moscow', -10]]

Summary

--Sort

Recommended Posts

When you want to sort a multidimensional list by multiple lines
When you want to play a game via Proxy
When you want to plt.save in a for statement
[Linux] When you want to search for a specific character string from multiple files
[Django] A memorandum when you want to communicate asynchronously [Python3]
When you want to hit a UNIX command on Python
When you want a long line break
When you want to replace multiple characters in a string without using regular expressions in python3 series
Gist repository to use when you want to try a little with ansible
I want to sort a list in the order of other lists
[Python] If you want to draw a scatter plot of multiple clusters
I made a program to notify you by LINE when switches arrive
How to write a string when there are multiple lines in python
Convert a multidimensional list (array) to one dimension
How to remember when you forget a word
What to do when you want to receive files from a Windows client remotely
[Python] I want to use only index when looping a list with a for statement
Settings when you want to run python-mecab with travis
When you want to filter with Django REST framework
Things to note when initializing a list in Python
[Python] I want to make a nested list a tuple
Python> Get a list of files in multiple directories> Use glob | Sort by modification time
Useful operation when you want to solve all problems in multiple programming languages with Codewars
When you want to quickly translate a C # sample into another language such as VB
A site to see when you want to read a machine learning paper but it seems difficult
Solution when you want to use cv_bridge with python3 (virtualenv)
[AWS] What to do when you want to pip with Lambda
Points to note when deleting multiple elements from the List
Use aggdraw when you want to draw beautifully with pillow
When you want to register Django's initial data with relationships
When you want to use multiple versions of the same Python library (virtual environment using venv)
[Subprocess] When you want to execute another Python program in Python code
What to do when a video cannot be read by cv2.VideoCapture
When you want to keep the Sphinx documentation theme as usual
Don't you want to say that you made a face recognition program?
When you want to print to standard output with print while testing with pytest
[Python] When you want to use all variables in another file
If you want to assign csv export to a variable in python
When you want to save the result of the callback function somewhere
I want to make a parameter list from CloudFormation code (yaml)
When you want to send an object with requests using flask
Pass a list by reference from Python to C ++ with pybind11
How to delete multiple specified positions (indexes) in a Python list
When you want to adjust the axis scale interval with APLpy
A note that you want to manually decorate the parameters passed in the Django template form item by item
Memorandum Regular expression When there are multiple characters in the character string that you want to separate
Extension of Python by C or C ++ (when there are multiple arguments, when passing a list from the Python side)
[Python] Sort iterable by multiple conditions
Key operations you want to know
When creating a matrix in a list
When you want to use it as it is when using it with lambda memo
I want to be cursed by a pretty girl every time I sudo! !!
When running a Python shell from Electron, pass multiple arguments to run Python.
[Introduction to Python] How to sort the contents of a list efficiently with list sort
When you want to change the HTTP headers of Flask's test client
If you want to get multiple statistics with groupby in pandas v1
[Google Colab] I want to display multiple images side by side in tiles
Wrapper when you want to output utf-8 + ansi color on Windows console
Memorandum of means when you want to make machine learning with 50 images
[Python] Try to make a sort program by yourself. (Selection sort, insertion sort, bubble sort)
[Question] I want to scrape a character string surrounded by unique tags!