When I was looking at the problem with CodeIQ for the first time in a while, I had a problem with sorting in Python3, and at that time I learned about sorting in Python3 for the first time, so I will record it here as a memo.
First, let's sort the elements in the list in ascending order.
The method used there is sort ()
.
If it is a character string, it will be sorted in the order of the character code, and if it is a numerical value, it will be sorted in ascending order.
exSort01.py
wordList = ["F","A","X"] #List of strings
numberList = [4,6,2] #List of numbers
wordList.sort()
print (wordList) #Output result:["A","F","X"]
numberList.sort()
print (numberList) #Output result:[2,4,6]
This time, I will try to reverse the order in which the elements are currently arranged. It uses a method called reverse ()
.
exSort02.py
wordList = ["F","A","X"] #List of strings
numberList = [4,6,2] #List of numbers
wordList.reverse()
print (wordList) #Output result:["X","A","F"]
numberList.reverse()
print (numberList) #Output result:[2,6,4]
As you can see, it is not sorted in descending order, it is just sorted in reverse order. So how do you sort in descending order ...
So, this time I would like to arrange them in descending order. You can easily do it by applying the learning so far.
A possible procedure is to first execute the sort
method to sort in descending order. And I think you can do it in descending order by executing the reverse
method.
So, I made it like this.
exSort03_01.py
wordList = ["F","A","X"] #List of strings
numberList = [4,6,2] #List of numbers
wordList.sort()
wordList.reverse()
print (wordList) #Output result:["X","F","A"]
numberList.sort()
numberList.reverse()
print (numberList) #Output result:[6,4,2]
did it! But, however. Two lines is awkward. Can you make it one line ... So, I rewrote it like this.
exSort03_01.py
wordList = ["F","A","X"] #List of strings
numberList = [4,6,2] #List of numbers
wordList.sort(reverse=True)
print (wordList) #Output result:["X","F","A"]
numberList.sort(reverse=True)
print (numberList) #Output result:[6,4,2]
Oh! It's done, and it's neat and tidy in one line!
I understand the one-dimensional sort. So, next is multidimensional sorting. For example, if you have the following list:
list = [[10,4],[3,6],[4,6],[5,0],[4,9],[2,0]]
So, let's sort this list first in ascending order by the first element, then in ascending order by the second element
[[2,0], [5,0], [10,4], [3,6], [4,6], [4,9]]
What if you want to get the result?
So, when I looked it up, there was an article titled "Sort by multiple keys", and there was an article titled "Student's grade list" in Japanese. It was written on the subject of wanting to sort in descending order of math scores (the article describes descending order). So, I referred to that and wrote the following!
exSort04.py
list = [[10,4],[3,6],[4,6],[5,0],[4,9],[2,0]]
list.sort(key=lambda x:x[0])
list.sort(key=lambda x:x[1])
print (list)
What this is doing is trying to sort in ascending order first. Among them, use the lambda expression
to select the key of the first element and ascend it, and then use the same lambda expression
to select the key of the second element. Ascending order. maybe....
It is used when creating a function like a def statement called lambda expression
, and it seems that the name comes from Lisp ... ("[[Python] [Study] Introduction to Python (27) --lambda expression" ](From http://atkonn.blogspot.jp/2008/02/python-python27-lambda.html) ”)
lambda argument 1, argument 2, ..., argument N: formula to find the answer you want to return
It seems to write like this. By the way, if you want to sort the first element in ascending order, compare the first same value with the second value, and ascend only that, you can write as follows.
exSort04.py
list = [[10,4],[3,6],[4,6],[5,0],[4,9],[2,0]]
list.sort(key=lambda x:(x[0],x[1]))
print (list)
It seems that there is a "secret in the standard comparison function cmp ()". For that, see the article "Sort by multiple keys".
It seems that there is also a method called sorted ()
for sorting, but this time it's a bonus.
I added feedback as soon as I received feedback from the problem provider. Very early!
The answer to the question was correct, but
"There is a way to use the ʻitemgetter method of the ʻoperator
module".
what is that? !! I looked it up.
Then, "9.9. Operator — standard operator in function format" and "[Sort HOW TO](http://docs.python .jp / 3.4 / howto / sorting.html) ”was found. The content of the story is useful for both, so if you haven't read it before, you may want to read it.
Well, let's get back to the story. Speaking from the conclusion, if you write as follows, the work so far is completed in one line!
exSort04.py
from operator import itemgetter
list = [[10,4],[3,6],[4,6],[5,0],[4,9],[2,0]]
list.sort(key=itemgetter(1,0))
print (list)
Beautiful.
This time I gave an example where the procedure is only twice, so it seems that the number of lines has not decreased because it contains the sentence " from operator import itemgetter
"that calls the ʻitemgetter method of the ʻoperator
module However, if this is done more than 3 times, the amount of description will definitely decrease.
If you look at the flow so far, you can understand why you should write list.sort (key = itemgetter (1,0))
, so I will explain it. If you don't understand, you may find out by looking at the contents of the following ʻitemgetter` method ...?
According to "10.3. Operator — Standard operator in function format", the ʻitemgetter` method looks like this: I wish I had it.
itemgetter method
def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
I see.
Recommended Posts