LoginSignup
1
1

More than 3 years have passed since last update.

【Python】スライスを使った降順表現

Posted at

はじめに

Pythonで配列の要素を逆順に並びかえる場合は、スライスを使って実装することができる。
降順に並び替える際にもこの手法はかなり便利である。
配列の操作をする場合によく使われるライブラリ「numpy」には「reverse」に相当する機能が存在していないが、スライスを使うことで簡単に逆順を表現できる。
ここでは、ランダムな数字が格納された配列aを降順ソートするサンプルプログラムを紹介していく。

アプローチ手順

numpyの「sort」を使って昇順に並び替えたあと、「[::-1]」で逆順に並び替える。

サンプルプログラム

Sample.py
import numpy as np

a = [2,5,4,12,8,3,6,0]

x = np.sort(a)[::-1]

for item in x:
  print(item)

出力結果

12
8
6
5
4
3
2
0
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1