Python内蔵関数zip()

6437 ワード

公式ドキュメントhttps://docs.python.org/2/library/functions.html#zipzip()の説明は次のとおりです.zip ([iterable, ...])
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length,  zip() is similar to  map()  with an initial argument of  None . With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n) . zip()  in conjunction with the  *  operator can be used to unzip a list:
>>>
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

New in version 2.0.
Changed in version 2.4: Formerly,  zip()  required at least one argument and  zip()  raised a  TypeError  instead of returning an empty list.
zip()はPythonの組み込み関数で、反復可能な一連のオブジェクトをパラメータとして受け入れ、オブジェクト内の対応する要素を順番にtupleに組み合わせ、各tupleには元のシーケンス内の対応するシーケンス番号の位置の要素が含まれ、これらのtuplesでグループ化されたlistを返します.入力パラメータの長さが等しくない場合、listの長さはパラメータの中で最も短いオブジェクトと同じです.すべてのパラメータの長さが同じ場合、zip()はmap()と同様であり、パラメータがない場合、zip()は空のlistを返します.
*番号オペレータを使用すると、list unzip(公式ドキュメントなどの基本例)を個別のシーケンスに解凍できます.
その他の例:
zipを使用して辞書を反転
>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> m.items()
[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
>>> zip(m.values(), m.keys())
[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
>>> mi = dict(zip(m.values(), m.keys()))
>>> mi
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

またzip()というよく使われない関数にもいくつかの高度な使い方があります.http://www.cnblogs.com/diyunpeng/archive/2011/09/15/2177028.html)
*2 Dマトリクス変換(行列の入れ替え)
例えば、リストで記述された2次元マトリクスがあり、pythonリストで導く方法で、このタスクを簡単に完了することができます.
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print [[row[col] for row in a] for col in range(len(a[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

もう1つの困惑する方法はzip関数を利用することです.
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> map(list,zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

この方法は速度が速いが理解しにくいため,listをtuple解凍と見なし,我々の「行列交換」の効果を適切に得,各要素にlist()関数を適用することでtupleをlistに変換する
*指定された確率で要素を取得
>>> import random
>>>
>>> def random_pick(seq,probabilities):
...     x = random.uniform(0, 1)
...     cumulative_probability = 0.0
...     for item, item_probability in zip(seq, probabilities):
...         cumulative_probability += item_probability
...         if x < cumulative_probability:
...             break
...     return item
...
>>> for i in range(15):
...     print random_pick("abc",[0.1,0.3,0.6]),
...
c a a c a c c c b b c a c b b

この関数には制限があり、指定確率のリストは要素と1つずつ対応しなければならず、1でなければ、この関数は予想通りに動作しない可能性があります.少し説明するにはrandomを利用する.uniform()関数は1つの0-1の間の乱数を生成してxにコピーし、zip()関数を利用して要素と彼の対応する確率をtupleにパッケージ化し、その後、各要素の確率をxより大きくループを終了するまで重畳し、「a」が選択された確率は、xが0-0.1に位置する確率であり、「b」が0.1-0.4、「c」が0.4-1.0である.xが0−1の間で平均的に値を取ったと仮定すると,我々の目的は明らかに達成された.