23
10

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.

pythonのソートで複数キーを指定するとき

Last updated at Posted at 2016-12-05

list.sort()とsorted()の違いについては触れない。
ソートするキーの指定について、こういう感じに書けるっぽい。2.7、たぶん3以降も同じ。

python2.7
from pprint import pprint

items = [
  {'id':2, 'book': {'type':'zassi', 'name': u'bbb' }},
  {'id':3, 'book': {'type':'manga', 'name': u'ccc' }},
  {'id':4, 'book': {'type':'zassi', 'name': u'ddd' }},
  {'id':1, 'book': {'type':'manga', 'name': u'aaa' }},
  {'id':5, 'book': {'type':'manga', 'name': u'eee' }},
]

# ソートキーが1つ
sorted_items = sorted(
  items,
  key = lambda x: x['id']
)
pprint(sorted_items)

#=>
#[{'book': {'name': u'aaa', 'type': 'manga'}, 'id': 1},
# {'book': {'name': u'bbb', 'type': 'zassi'}, 'id': 2},
# {'book': {'name': u'ccc', 'type': 'manga'}, 'id': 3},
# {'book': {'name': u'ddd', 'type': 'zassi'}, 'id': 4},
# {'book': {'name': u'eee', 'type': 'manga'}, 'id': 5}]


# ソートキーが2つ以上
sorted_items = sorted(
  items,
  key = lambda x: (x['book']['type'], x['id'])
)
pprint(sorted_items)

#=>
#[{'book': {'name': u'aaa', 'type': 'manga'}, 'id': 1},
# {'book': {'name': u'ccc', 'type': 'manga'}, 'id': 3},
# {'book': {'name': u'eee', 'type': 'manga'}, 'id': 5},
# {'book': {'name': u'bbb', 'type': 'zassi'}, 'id': 2},
# {'book': {'name': u'ddd', 'type': 'zassi'}, 'id': 4}]

後書いてて気づいたのは、itemgetterとかattrgetterは同じ階層のしかみないっぽいので例えば [{book:{},shelf:{}}, {book:{},shelf:{}}] みたいな構造だとbookのこれとshelfのこれみたいなキーの指定はできないっぽい気がする。 -> これらは使わずにタプルで指定すればいける

23
10
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
23
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?