4
4

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.

Looping idioms in Python

4
Last updated at Posted at 2015-03-13

Abstruction

Pythonのループの書き方を紹介していきます。 Pythonのinteractive shell の実行結果を最初に紹介していくので、実際に自分で書いて実行してみるとわかりやすいと思います。

>>> # Let's create lists

>>> colors = "red blue green yellow".split()
>>> colors
['red', 'blue', 'green', 'yellow']

Vanilla way to loop over data

listのindexを指定してデータを取り出す方法

>>> for i in [0, 1, 2, 3]:
	print colors[i]

	
red
blue
green
yellow

Classical way to loop over data

[0, 1, 2, 3]range(len(colors))で取得できるのでrangeを使ったイテレーション

>>> range(4)
[0, 1, 2, 3]
>>> for i in range(len(colors)):
	print colors[i]

	
red
blue
green
yellow

Pythonic way to iterate data.

iteratableなデータ(ループできるデータ)はindexを指定することなく、inのあとに書くことにより、すべてをイテレーションすることができる。下記のコードは上記の2つと等価です。

>>> for i in colors:
	print i

	
red
blue
green
yellow

Vanilla way to iterate data in reversed order


>>> for i in [3, 2, 1, 0]:
	print colors[i]

	
yellow
green
blue
red

Classical way to iterate data in reversed order

rangeは第一引数として、始まりの値、第二引数として終わりの値、第三引数として、増減の値を指定できる。これにより、indexの逆の順番のリストを生成できる。

>>> range(3, 0, -1)
[3, 2, 1]
>>> range(3, -1, -1)
[3, 2, 1, 0]
>>> range(len(colors) - 1, -1, -1)
[3, 2, 1, 0]

>>> for i in  range(len(colors) - 1, -1, -1):
	print colors[i]

	
yellow
green
blue
red

Pythonic way way to iterate data in reversed order

逆の順番でやりたいのなら、reversedというbuild-in関数が使える。

>>> for i in reversed(colors):
	print i

	
yellow
green
blue
red

list[::-1]という文法も使える. が, reversedのほうが明示的であると思われる。

>>> for color in colors[::-1]:
     print color

yellow
green
blue
red

Vanilla way to iterate data with index number

>>> for i in range(len(colors)):
	print i, "-->", colors[i]

	
0 --> red
1 --> blue
2 --> green
3 --> yellow

Pythonic way to iterate data with index number

enumerateは、index numberとvalueをtupleで返すiteratorを返す。

>>> enumerate(colors)
<enumerate object at 0x106e55690>
>>> list(enumerate(colors))
[(0, 'red'), (1, 'blue'), (2, 'green'), (3, 'yellow')]
>>> for i, color in enumerate(colors):
	print i, "-->", color

	
0 --> red
1 --> blue
2 --> green
3 --> yellow

Iterate data with sorted function

文字列をソート

>>> for color in sorted(colors):
     print color

blue
green
red
yellow

逆順でソート

>>> for color in sorted(colors, reverse=True):
     print color

yellow
red
green
blue

文字の長さ順でソート

>>> for color in sorted(colors, key=len):
     print color

red
blue
green
yellow

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?