3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2次元配列や辞書や独自クラスのリストのソートの方法

Last updated at Posted at 2016-07-04

2次元配列のソート

>>> 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]]    # 2番目の要素でソート
>>> hoge
[[10, 4], [4, 9], [5, 0], [4, 5], [2, 0], [3, 5]]    # sortedでは元の配列は変化しない
>>> hoge.sort(key=lambda x:x[0])
>>> hoge
[[2, 0], [3, 5], [4, 9], [4, 5], [5, 0], [10, 4]]    # 先頭要素でソートすると [4, 9], [4, 5] の順序
>>> hoge.sort()
>>> hoge
[[2, 0], [3, 5], [4, 5], [4, 9], [5, 0], [10, 4]]    # 全要素でソートすると [4, 5], [4, 9] の順序

辞書をソート by key

>>> d = {'Yamada': 100, 'Sato': 50, 'Kobayashi': 75}
>>> sorted( d.items() )
[('Kobayashi', 75), ('Sato', 50), ('Yamada', 100)]

辞書をソート by value

>>> sorted(d.items(), key=lambda x:x[1])
[('Sato', 50), ('Kobayashi', 75), ('Yamada', 100)]

独自クラスのリストをソート

準備

>>> 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
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?