for...in

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(Omi Chiba)

for...in

Pythonでは反復可能なオブジェクトをループで回すことができます。

In Python, you can loop over iterable objects:

1.

2.

3.

4.

5.

6.

7.

>>> a = [0, 1, 'hello', 'python']

>>> for i in a:

print i

0

1

hello

python

xrangeは一般的なショートカットの1つで、すべてのリスト要素を格納せずに、反復可能な範囲オブジェクトを生成します。

One common shortcut is xrange, which generates an iterable range without storing the entire list of elements.

1.

2.

3.

4.

5.

6.

>>> for i in xrange(0, 4):

print i

0

1

2

3

これは、次のC / C + + / C#の/ Javaの構文と等価です:

This is equivalent to the C/C++/C#/Java syntax:

1.

for(int i=0; i<4; i=i+1) { print(i); }

もう1つの有用なコマンドはenumerateです。次のようにカウントしながらループ処理を行います:

Another useful command is enumerate, which counts while looping:

1.

2.

3.

4.

5.

6.

7.

>>> a = [0, 1, 'hello', 'python']

>>> for i, j in enumerate(a):

print i, j

0 0

1 1

2 hello

3 python

また、range(a, b, c)というキーワードがあります。これは、aで始まりcずつ増加し、bより小さい最後の値で終わる整数のリストを返します。aはデフォルト値で0で、cはデフォルトで1です。xrangeも似ていますが実際にリストを作ることはなく、そのリストに対するイテレータを生成します。これはループ処理にとってより良いです。

There is also a keyword range(a, b, c) that returns a list of integers starting with the value a, incrementing by c, and ending with the last value smaller than b, a defaults to 0 and c defaults to 1. xrange is similar but does not actually generate the list, only an iterator over the list; thus it is better for looping.

breakを利用してループから抜けることができます。

You can jump out of a loop using break

1.

2.

3.

4.

>>> for i in [1, 2, 3]:

print i

break

1

continueを利用して、すべてのコードブロックを実行せずに、次のループ処理へ飛ぶことができます:

You can jump to the next loop iteration without executing the entire code block with continue

1.

2.

3.

4.

5.

6.

7.

>>> for i in [1, 2, 3]:

print i

continue

print 'test'

1

2

3