LoginSignup
9
11

More than 5 years have passed since last update.

Python3系の基礎文法(Pythonの反復処理をいくつか)

Posted at

概要

O'Reilly Japan の「入門 Python 3」を参考に、Python3系の基礎文法を勉強します。
同じようにPythonを勉強したいと思ってる方の参考になれば幸いです。

反復処理

反復処理により、リストの値の取り出すコードを比較してみる。

普通に書いた反復処理

>>> target = ['AAA', 'BBB', 'CCC']
>>> current = 0
>>> while current < len(target):
...     print(target[current])
...     current += 1
...
AAA
BBB
CCC

Pythonらしく書いた反復処理

>>> target = ['AAA', 'BBB', 'CCC']
>>> for out in target:
...     print(out)
...
AAA
BBB
CCC

2つ目のコードの方が、Pythonらしい良いコードになる。
リストはPythonのイテラブル(イテレータに対応している)オブジェクトであるため、for文で処理すると、リストの要素が一つずつ取り出される。

for文

リストの他にも、文字列、タプル、辞書、集合、その他のようにPythonのイテレータオブジェクトが存在する。

文字列

>>> target = 'python'
>>> for out in target:
...     print(out)
...
p
y
t
h
o
n

辞書

キーの取り出し(その1)

>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num:
...     print(out)
...
0
1
2

キーの取り出し(その2)

>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num.keys():
...     print(out)
...
0
1
2

値の取り出し

>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num.values():
...     print(out)
...
zero
one
two

タプル形式での取り出し

>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for out in num.items():
...     print(out)
...
(0, 'zero')
(1, 'one')
(2, 'two')

タプル形式での取り出し(応用)

取り出しと代入をワンステップで処理する場合

>>> num = {0:'zero', 1:'one', 2:'two'}
>>> for key, value in num.items():
...     print('key:', key, 'value:', value)
...
key: 0 value: zero
key: 1 value: one
key: 2 value: two

zip()を使った反復処理

zip()を使うと、複数のシーケンスを並列的に反復処理できる。

>>> list1 = ['1', '2', '3']
>>> list2 = ['A', 'B', 'C']
>>> list3 = ['one', 'two', 'three']
>>> for out1, out2, out3 in zip(list1, list2, list3):
...     print('list1:', out1, 'list2', out2, 'list3', out3)
...
list1: 1 list2 A list3 one
list1: 2 list2 B list3 two
list1: 3 list2 C list3 three

zip()の返却値でリストを生成

>>> list1 = ['1', '2', '3']
>>> list2 = ['A', 'B', 'C']
>>> list( zip(list1, list2) )
[('1', 'A'), ('2', 'B'), ('3', 'C')]

zip()の返却値で辞書を生成

>>> list1 = ['1', '2', '3']
>>> list2 = ['A', 'B', 'C']
>>> dict( zip(list1, list2) )
{'1': 'A', '2': 'B', '3': 'C'}

range()による数値シーケンスの作成

動作イメージ

>>> for x in range(0, 3):
...     print(x)
...
0
1
2

数値シーケンスのリスト作成

>>> list( range(0, 3) )
[0, 1, 2]
9
11
2

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
9
11