Python入門トップページ


目次

  1. プログラミング言語
  2. Anaconda - Jupyter Notebook / JupyterLab の環境設定
  3. Python の基礎
  4. リスト,タプル,辞書,集合
  5. 再び Jupyter Notebook の操作
  6. Python の制御構文
  7. 関数
  8. 便利な関数など
    1. 最大・最小
    2. 並べ替え(ソート)
    3. 値の入れ替え
  9. リストの内包表記
  10. 多次元リスト
  11. クラス
  12. 演習問題
  13. 雑多な情報

Python の基礎

便利な関数など

並べ替え(ソート)

リストを並べ替えるためのアルゴリズムには様々なもの(シェルソート,バブルソート,マージソート,クイックソートなど)があり,それぞれの特徴を理解し,適切なアルゴリズムを利用して,自分でコードを書けるようになるべきである.しかしながら,Python ではリストのソートに関しても関数が準備されている.リスト関数である sort() は,リスト自体をソートする(つまり,リスト自体を書き換える).

# リストをソートする
scores = [30, 60, 55, 40]
scores.sort()
print(scores)
[30, 40, 55, 60]

降順でソートするには reverse=True 引数を追加すると良い.

# リストを降順でソートする
scores = [30, 60, 55, 40]
scores.sort(reverse=True)
print(scores)
[60, 55, 40, 30]

一方で,汎用関数の sorted() は,ソートされたリストのコピーを返す(つまり,リストを書き換えない).

# socores リストをソートした結果を sorted_scores リストに代入する
scores = [30, 60, 55, 40]
sorted_scores = sorted(scores)
print(sorted_scores)
print(scores) # リストは書き換えられていない
[30, 40, 55, 60]
[30, 60, 55, 40]

sort() 関数と同様に,降順でソートするには reverse=True 引数を追加すると良い.

# socores リストを降順でソートした結果を sorted_scores リストに代入する
scores = [30, 60, 55, 40]
sorted_scores = sorted(scores, reverse=True)
print(sorted_scores)
print(scores) # リストは書き換えられていない
[60, 55, 40, 30]
[30, 60, 55, 40]

目次に戻る