python3

python3 でタプルを指定した要素で順に並び替える

投稿日:2020年12月3日 更新日:

タプルを、指定した要素で並び替えることができる。

「key=lambda x 」で、引数 x を指定。lambda は無名関数を表す。

record = [('織田信長', 1534, 1582), ('豊臣秀頼', 1593, 1615), ('徳川家康', 1543, 1616)]

# 2番目の要素で並び替え
record.sort(key=lambda x: x[1], reverse=False) 
print(record)

# 3番目の要素で並び替え
record.sort(key=lambda x: x[2], reverse = False)
print(record)

結果

[('織田信長', 1534, 1582), ('徳川家康', 1543, 1616), ('豊臣秀頼', 1593, 1615)]
[('織田信長', 1534, 1582), ('豊臣秀頼', 1593, 1615), ('徳川家康', 1543, 1616)]

-python3
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

python のプロンプトについて

UNIX で python を起動する ターミナルで $ python インタープリターのプロンプトは >>> となっている。 インタープリタを終了させるときは、Ctrl + D を押す。

no image

matplotlib で複数のグラフを並べて表示する方法

plot.subplots() でグラフの縦方向と横方向の数を指定する。 例 import numpy as np from matplotlib import pyplot as plt x1 = …

no image

matplotlib で、グラフの線の幅を変更する方法

lw で、線幅を数字で指定すればよい。 例 from matplotlib import pyplot as plt data_x = [25,26,27] data_y = [39, …

no image

pythonで配列(リスト)の、ある要素がわかっているときにその次の要素を取得する方法。

リストを iter に変えたあと、… next() を使う。 参考リンク https://www.programiz.com/python-programming/methods/buil …

no image

python3 でリストの要素を None に変更する方法

要素を None に変更すればよい。 例 arr = [1,2,3,4,5] print(str(arr)) for i in range(len(arr)): arr[i] = No …