Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Python の式でリストのリストを並べ替えたいと思います。
つまり、リストのリストを の値でソートします。abs(x[0] - x[3])ここxで、 はサブリストです。リストに別の要素を追加し、それを並べ替えて削除することでそれを行うことができますが、それは非効率的です。より良い方法はありますか?
abs(x[0] - x[3])
x
ソートするキー関数として渡すだけです:
my_list.sort(key=lambda x: abs(x[0] - x[3]))
例えば:
In [1]: my_list = [[1, 2], [3, 7], [4, 6]] In [2]: my_list.sort(key=lambda x: abs(x[0] - x[1])) In [3]: my_list Out[3]: [[1, 2], [4, 6], [3, 7]]