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

python3 で、dictionary のキー一覧を取得する方法

dict.keys() でキーを取得することができる。 参考:dictionary の値一覧を取得するときは、dict.values() を使う。 例 print(dict.keys())

no image

python3 でグローバル変数とローカル変数で同じ名前の変数を使う

グローバル変数とローカル変数で同じ名前の変数を使うことができる。 例 x = 10 def myfunc(): x = 20 print(‘関数内: x = ‘+str(x)) myfunc() pr …

no image

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

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

no image

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

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

no image

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

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