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

python3 で文字列を入力させて受け取る方法

C言語で scanf のようなものを作るには、python では input() で実現できる。 例 print(‘xの値を入力してください’) x = input() print(‘xの値は ‘ + …

no image

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

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

no image

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

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

no image

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

next() を使う。 例 my_arr = [‘春’,’夏’,’秋’,’冬’] my_iter = iter(my_arr) print(next(my_iter,’なし’)) print(next …

no image

matplotlib で、縦横の線(グリッド)を描く方法

pyplot grid で縦横線(罫線のようなもの)を引くことができる。 例 from matplotlib import pyplot as plt data_x = [25,26,27] …