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で配列(リスト)の、ある要素がわかっているときにその次の要素を取得する方法。

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

no image

matplotlib で、軸に垂直・平行な線を書く方法

axhline, axvline を使ってx,y軸に平行な線を描くことができる。 https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot …

no image

matplotlib で、ヒストグラムを作成する方法

ヒストグラムを描くには、data_hist を使う。 ヒストグラムの縦棒の数は bins で指定する。 例 from matplotlib import pyplot as plt data_hist …

no image

gnuplot で、グラフの形を正方形にする方法

set size square または、その省略形で set size sq というコマンドを使えば正方形の中にグラフを描くことができる。 例 set size square plot cos(x) …

no image

python3 で、csv ファイルを読み込んで条件をみたす行の内容を表示する方法

csv.reader で読み込み、各行を読み込んで判定する。 例 import csv with open(‘data.csv’, ‘r’) as csv_file: reader = csv.rea …