リストの逆順
Pythonにてリストの逆順を取得したい場合があります。
指定のリスト自体を逆順に変更する方法と、リストの逆順結果のみを取得する方法がありますので使い分けましょう。
下記サンプルをご覧ください。
# -*- coding: utf-8 -*- if __name__ == "__main__": python_list = [] python_list.append("python") python_list.append("izm") python_list.append("sample") python_list.append("list") python_list.append("reversed") print "---------------------------------" print u"【そのまま表示】" for value in python_list: print value python_list.reverse() print "---------------------------------" print u"【逆順表示】" for value in python_list: print value
--実行結果--
--------------------------------- 【そのまま表示】 python izm sample list reversed --------------------------------- 【逆順表示】 reversed list sample izm python
リスト「python_list」の内包している値自体が逆順ソートされています。
内包している値を変更したくない際には次の方法を試してみましょう。
結果のみを取得し、リスト自体を変更したくない場合のサンプルです。
# -*- coding: utf-8 -*- if __name__ == "__main__": python_list = [] python_list.append("python") python_list.append("izm") python_list.append("sample") python_list.append("list") python_list.append("reversed") print "---------------------------------" print u"【そのまま表示】" for value in python_list: print value print "---------------------------------" print u"【逆順表示】" for value in reversed(python_list): print value print "---------------------------------" print u"【リストの再表示】" for value in python_list: print value
--実行結果--
--------------------------------- 【そのまま表示】 python izm sample list reversed --------------------------------- 【逆順表示】 reversed list sample izm python --------------------------------- 【リストの再表示】 python izm sample list reversed
「reversed」関数を使用します。
表示結果からリスト「python_list」自体の変更はされていないのが確認出来ると思います。
|
|
|
|
インデックスと値を同時に取り出します!
▶応用編:リストのインデックス