Python.use(better)《余録》組み込み関数 zip

記事一覧入門編基礎編応用編中級編

Python.use(better)
《余録》組み込み関数 zip

《著》小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28

組み込み関数 range

>>> print(zip.__doc__)
zip(iter1 [,iter2 [...]]) --> zip object

Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument.  The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.
■ 組み込み関数 zip
$ python builtin_function.py
>>> do()
...
>>> # -------------------------------------------------- tips_zip
>>> s1 = "ABC"; s1
'ABC'
>>> s2 = "123"; s2
'123'
>>> s = zip(s1,s2); s; list(s)

[('A', '1'), ('B', '2'), ('C', '3')]

組み込み関数 zip を利用すると、

  • 複数のシーケンスに含まれる「各要素を列挙したタプル」を列挙したリストが得られます。
■ for 文
>>> for e1,e2 in zip(s1,s2):
        print(e1+e2)

A1
B2
C3

for 文を利用すると、

  • in に続くシーケンスの各要素 e1,e2 を順に参照しながら、
  • for ブロックにある、コードの断片を実行します。

そのため、各行には、複数のシーケンス s1,s2 に含まれる「各要素を連結した文字列」が出力されます。

>>> s1 = "ABC"; s1
'ABC'
>>> s2 = "12"; s2
'12'
>>> for e1,e2 in zip(s1,s2):
        print(e1+e2)

A1
B2

ただし、対応する要素がないときには、なにも得られません。つまり、最も短いシーケンスに依存します。

》こちらに移動中です《
TOP


関連記事

Last updated♪2009/10/26