python3

python3 で、配列の配列をソートする

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

ラムダ式を使って、任意の要素についてソートすることができる。

arr = [[1,2,3],[2,1,2],[3,3,4],[4,4,1]]

for i in range(0,3):
    arr.sort(key=lambda x: x[i]) 
    print(str(i) + '番目でソート: ' + str(arr))

結果

0番目でソート: [[1, 2, 3], [2, 1, 2], [3, 3, 4], [4, 4, 1]]
1番目でソート: [[2, 1, 2], [1, 2, 3], [3, 3, 4], [4, 4, 1]]
2番目でソート: [[4, 4, 1], [2, 1, 2], [1, 2, 3], [3, 3, 4]]

参考

例では昇順に並べている。降順に並べたいときは、sort のオプションで「reverse=True」と指定すれば良い。


-python3
-

執筆者:


comment

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

関連記事

no image

matplotlib でエラーバーを設定する方法

pyplot.errorbar を使って設定する。 オプションの詳細は https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.erro …

no image

python でファイルを1行おきに読み込む方法

readline を使って次のように書く。 例 ファイル:data.txt # id name age 1 佐藤太郎 10 2 鈴木花子 18 3 坂本明美 21 4 松村光子 24 5 小川奏子 1 …

no image

matplotlib でグラフ表示ウィンドウの画面上の位置を自由に設定する方法

matplotlib.use(‘TkAgg’) としておき、 get_current_fig_manager().window.wm_geometry(“+20+50”) として、(+20+50)のと …

no image

python3 で、csv ファイルの日付・数字を読み取る方法

csv をインポートすると、row in reader はリストになっている。 次のようにして、各行の要素を取り出して表示することができる。 例 import csv with open(‘data. …

no image

python3 で整数の割り算、商と余りを求める方法

floor divisionを使う。 例 a = 15 // 7 b = 15 % 7 print(a) print(b) 結果 2 1