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 で辞書からタプルを作成する

辞書に対して、items() メソッドを使うと、タプルを作成することができる。 例 cities = {‘東京’:1000,’大阪’:700, ‘広島’:100} for a,b in cities. …

no image

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

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

no image

matplotlib で、複数のグラフを簡単にプロットする方法

変数を並べて書くと、次のように自動的に順番を理解してグラフを表示してくれる。 例 import numpy as np from matplotlib import pyplot as plt fro …

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 …