【python】zip関数の動作を詳細に理解するデータ再編成
9629 ワード
zip()はPythonの組み込み関数で、一連の反復可能なオブジェクトをパラメータとして受け入れ、オブジェクト内の対応する要素を個々のtuple(メタグループ)にパッケージ化し、これらのtuplesからなるlist(リスト)を返します.入力パラメータの長さが等しくない場合、listの長さはパラメータの中で最も短いオブジェクトと同じです.*番号オペレータを使用してlist unzip(解凍)を使用します.
1、生成されたxyzはzipオブジェクトである
2、不等リストのzip
3、zip(*)はzipの逆過程である
4、二次元マトリックス変換(マトリックスの行列交換)
5、zip関数辞書をリスト形式に反転する
6、zipがリストを生成する方法
1、生成されたxyzはzipオブジェクトである
In [1]: x = [1, 2, 3]
...: y = [4, 5, 6]
...: z = [7, 8, 9]
...: xyz = zip(x, y, z)
# xyz zip
In [2]: xyz
Out[2]: 0x14120b9fac8>
# list zip ,zip
In [3]: list(xyz)
Out[3]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
2、不等リストのzip
# zip , zip
In [4]: h = [2,3,4,5]
In [5]: xyzh = zip(x,y,z,h)
In [6]: xyzh
Out[6]: 0x14122b44f88>
#h
In [7]: list(xyzh)
Out[7]: [(1, 4, 7, 2), (2, 5, 8, 3), (3, 6, 9, 4)]
3、zip(*)はzipの逆過程である
#zip(*) zip ·
x = [1, 2, 3] #unzip zip
y = [4, 5, 6]
z = [7, 8 ,9]
xyz = zip(x, y, z)
zyx = zip(*xyz) # *xyz xyz zip, xyz , zip
print(list(zyx)) #xyz :xyz=[[1, 4, 7], [2, 5, 8], [3, 6, 9]] zip(*xyz)=>zip([1, 2, 3],[4, 5, 6],[7, 8, 9])
4、二次元マトリックス変換(マトリックスの行列交換)
#
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# python ,
[[row[col] for row in a] for col in range(len(a[0]))]
# zip :
In [18]: list(zip(a[0],a[1],a[2]))
Out[18]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
In [20]: list(zip(*a))
Out[20]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
In [22]: list( map(list,zip(*a)))
Out[22]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# , list tuple , “ ” , list() , tuple list
5、zip関数辞書をリスト形式に反転する
x = {'age':18,'name':'dh','id':3306}
# ( , )
In [26]: x.items()
Out[26]: dict_items([('name', 'dh'), ('age', 18), ('id', 3306)])
In [27]: x = zip(x.values(),x.keys())
In [28]: x
Out[28]: at 0x202ce13b248>
In [29]: list(x)
Out[29]: [('dh', 'name'), (18, 'age'), (3306, 'id')]
6、zipがリストを生成する方法
# :
#1: [x] x
#2: [x]*2 * 2
#3: zip(* [x] * 2) zip(x, x)
In [30]: x = [1, 2, 3, 4]
...: y = zip(* [x] * 2)
In [31]: y
Out[31]: 0x202cef0ea88>
In [32]: list(y)
Out[32]: [(1, 1), (2, 2), (3, 3), (4, 4)]
In [35]: list(zip(*[x]))
Out[35]: [(1,), (2,), (3,), (4,)]
In [36]: list(zip(*[x]*2))
Out[36]: [(1, 1), (2, 2), (3, 3), (4, 4)]