>>> hoge = [[10,4],[4,9],[5,0],[4,5],[2,0],[3,5]]
>>> sorted(hoge)
[[2, 0], [3, 5], [4, 5], [4, 9], [5, 0], [10, 4]]
>>> sorted(hoge, key=lambda x:x[1])
[[5, 0], [2, 0], [10, 4], [4, 5], [3, 5], [4, 9]]    #Sort by second element
>>> hoge
[[10, 4], [4, 9], [5, 0], [4, 5], [2, 0], [3, 5]]    #Sorted does not change the original array
>>> hoge.sort(key=lambda x:x[0])
>>> hoge
[[2, 0], [3, 5], [4, 9], [4, 5], [5, 0], [10, 4]]    #When sorting by the first element[4, 9], [4, 5]The order of
>>> hoge.sort()
>>> hoge
[[2, 0], [3, 5], [4, 5], [4, 9], [5, 0], [10, 4]]    #If you sort by all elements[4, 5], [4, 9]The order of
>>> d = {'Yamada': 100, 'Sato': 50, 'Kobayashi': 75}
>>> sorted( d.items() )
[('Kobayashi', 75), ('Sato', 50), ('Yamada', 100)]
>>> sorted(d.items(), key=lambda x:x[1])
[('Sato', 50), ('Kobayashi', 75), ('Yamada', 100)]
Preparation
>>> class Seiseki:
...     def __init__(self, name, tensu):
...             self.name = name
...             self.tensu = tensu
...     def output(self):
...             print("Name:{0}, Tensu:{1}".format(self.name, self.tensu))
... 
>>> ll = [Seiseki('Yamada', 100), Seiseki('Sato', 50), Seiseki('Kobayashi', 75)]
>>> for l in ll:
...     l.output()
Name:Yamada, Tensu:100
Name:Sato, Tensu:50
Name:Kobayashi, Tensu:75
sort by name
>>> ll.sort(key=lambda x: x.name)
>>> for l in ll:
...     l.output()
... 
Name:Kobayashi, Tensu:75
Name:Sato, Tensu:50
Name:Yamada, Tensu:100
sort by tensu
>>> ll.sort(key=lambda x: x.tensu)
>>> for l in ll:
...     l.output()
... 
Name:Sato, Tensu:50
Name:Kobayashi, Tensu:75
Name:Yamada, Tensu:100
Recommended Posts