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 で、線の種類を変更する方法

「linestyle = 」として、線の種類を指定することができる設定の詳細は、次のリンクを参照。 https://matplotlib.org/stable/gallery/lines_bars_a …

no image

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

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

no image

python3 でリストを結合する方法

2つのリストを結合して、「リストのリストを作りたい場合」と、「1つの長いリストを作りたい」場合がある。 それぞれ、次のようにする。 例 # リスト2つを用意 l_1 = [1,2,3] l_2 …

no image

matplotlib で、凡例を表示する方法

データに label を関連付け、plt.legend() で凡例を表示する。 例 from matplotlib import pyplot as plt data_x = [25,26,2 …

no image

python3 で、すべて小文字かどうかを判定する方法

islower() 関数を使う。 例 print(‘abcde’.islower()) print(‘abcDe’.islower()) 結果 True False