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']
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.
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]]
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]]
--Sort
sorted(a, key=lambda x:(x[i], x[j], x[k], ...)
--sort ()
is ** sorted by the basic first row, but for columns with the same elements in the first row, it is sorted by comparing the next second row **