>>> 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]] #Trier par deuxième élément
>>> hoge
[[10, 4], [4, 9], [5, 0], [4, 5], [2, 0], [3, 5]] #Trié ne modifie pas la séquence d'origine
>>> hoge.sort(key=lambda x:x[0])
>>> hoge
[[2, 0], [3, 5], [4, 9], [4, 5], [5, 0], [10, 4]] #Tri par le premier élément[4, 9], [4, 5]L'ordre de
>>> hoge.sort()
>>> hoge
[[2, 0], [3, 5], [4, 5], [4, 9], [5, 0], [10, 4]] #Si vous triez par tous les éléments[4, 5], [4, 9]L'ordre de
>>> 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)]
Préparation
>>> 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