3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

リスト逆順操作

Last updated at Posted at 2012-08-25

よく使うリスト逆順操作について

>>> list = [1,2,3]
>>> reversed(list) # => <listreverseiterator object>
>>> list.reverse() # => 破壊的操作
>>> list
[3,2,1]
>>> list = [1,2,3]
>>> list[::-1]     # => 最も単純かつ強力
[3,2,1]

逆順のリストに函数を適用する場合

>>> list = [1,2,3]
>>> def inc(n):
...     return n+1
...
>>> # 冗長だが分かりやすい
>>> for i in reversed(list):
...     print inc(i)
...
4
3
2
>>> # 破壊的操作であるため注意が必要
>>> list.reverse()
>>> for i in list:
...     print inc(i)
...
4
3
2
>>> list = [1,2,3]
>>> map(inc, list[::-1]) # => 簡潔かつ強力
[4, 3, 2]
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?