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

matplotlib で、凡例を表示する位置を変更する方法

凡例(legend)の表示位置を変更するには、axis の legend の loc を設定する。 次のリンクhttps://matplotlib.org/stable/api/_as_gen/mat …

no image

matplotlib でcsv ファイルを読み込むとき、最初の行をスキップする方法

numpy の loadtxt で読み込む行を省略したい場合 スキップしたい行を # 等の記号でコメントアウトして、 loadtxt の comments = ‘#’ とすると …

no image

python3 で、リストを pop したものの返り値

リストを pop すると、 pop された値が返される。 例 plant_1 = [’pumpkin’, ‘ginger’, ‘potato’] plant_2 = [] print( …

no image

matplotlib で散布グラフを描く方法

pyplt.scatter を使って散布グラフを描くことができる。 点の色は、点ごとに変えることができる。 下の例では color の配列で点の色を指定している。 例 from matplotlib …

no image

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

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