Python使用技巧(十):zip(x,y)模組
阿新 • • 發佈:2020-12-16
技術標籤:python使用技巧python
一、利用zip函式將兩個列表(list)組成字典(dict)
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary)
二、 合併兩列表
a = [1, 2, 3]
b = (4, 5, 6)
z = zip(a, b)
for i in z:
print(i)
按行輸出:
a = [ [1,2,3], [4,5,6], [7,8,9] ]
for v in a:
print(v)
轉為字典行駛:
a = [1, 2, 3]
b = (4, 5, 6)
z = zip(a, b)
z2 = list(z)
z3 = dict(z2)
print(z3)
三、去掉zip中的括號後轉化為陣列與列表
b = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
np.array(b)
Out[86]:
array([[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6],
[6, 7]])
(np.array(b) ).tolist()
Out[87]: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
四、將zip合併的資料儲存在csv
a=[1,2,3]
b=[4,5,6]
zip(a,b)
Out[93]: <zip at 0x1a8ebced388>
import csv
with open('text.csv', 'w') as f:
...: writer = csv.writer(f, delimiter='\t')
...: writer.writerows(zip(a,b))