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.
正と負の要素を含むこのリストがありますが、リストを並べ替えて絶対値にする必要があります。次に例を示します。
list[-2,-3,8,-5,1,7]===>list[1,2,3,5,7,8] 明確ですか? コード:
a=5 b=6 c=-3 d=-8 lista = [a,b,c,d] lista.sort() lista.reverse()
lista = [-2, -3, 8, -5, 1, 7] lista.sort(key=abs) lista
上記のコードを試すことができます。
それらを絶対値で並べ替えたいが、リストは元の値を維持する場合:
lista = [-2, -3, 8, -5, 1, 7] lista.sort(key=lambda x: abs(x)) lista Out: [1, -2, -3, -5, 7, 8]