1
2

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.

「ゼロから始めるデータサイエンス」1章で使うsorted関数のエラーについて

Last updated at Posted at 2017-11-19

python3で取り組んでいる方向け

僕が読んだ本のまま進めると、sorted関数でエラーがでました。
日本語の回答がなかったのですが、解決方法を見つけたので書いておきます。

※変数名と値をすこし変えて書いていきます

# 左([0])の値はuser_id,右([1])は友達の人数だとします。
friends = [(0, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 4), (6, 2), (7, 2), (8, 3), (9, 1)]

# 友達の人数順にソートしたいのですが、ここでエラーが出る。
sorted(friends,key=lambda (x,y):x,reverse=True)

エラーの内容は下記の通りです

tuple parameter unpacking python 3 sorted

python3だとsorted関数内でタプル(丸括弧で囲ってる値)は使えないよ〜って内容だと思います。

この問題への解決方法

itemgetterというのを呼び出して、keyに指定することで解決しました!

# ファイルの頭に書いてください。
from operator import itemgetter

friends = [(0, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 4), (6, 2), (7, 2), (8, 3), (9, 1)]

sorted(friends, key=itemgetter(1), reverse=True)
>>> #[(3, 4), (5, 4), (1, 3), (2, 3), (8, 3), (0, 2), (4, 2), (6, 2), (7, 2), (9, 1)]

無事友達の人数順に出力されました!!!

P.S.

@shiracamusさんから「itemgetter呼ばなくても同じように書けるよ!」と教えて頂きました!

friends = [(0, 2), (1, 3), (2, 3), (3, 4), (4, 2), (5, 4), (6, 2), (7, 2), (8, 3), (9, 1)]

sorted(friends, key=lambda item:items[1], reverse=True)
>>> #[(3, 4), (5, 4), (1, 3), (2, 3), (8, 3), (0, 2), (4, 2), (6, 2), (7, 2), (9, 1)]

僕が覚えた方法より簡潔で勉強になります!
ありがとうございました😊

1
2
2

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?