前言 |
zip(*iterables)函數詳解 |
傳入參數:
元組、列表、字典等迭代器。python
當zip()函數中只有一個參數時
zip(iterable)
從iterable中依次取一個元組,組成一個元組。git
示例:github
## zip()函數單個參數 list1 = [1, 2, 3, 4] tuple1 = zip(list1) # 打印zip函數的返回類型 print("zip()函數的返回類型:\n", type(tuple1)) # 將zip對象轉化爲列表 print("zip對象轉化爲列表:\n", list(tuple1))
輸出:微信
zip()函數的返回類型:
<class 'zip'>
zip對象轉化爲列表:
[(1,), (2,), (3,), (4,)]
機器學習
zip(a,b)
zip()函數分別從a和b依次各取出一個元素組成元組,再將依次組成的元組組合成一個新的迭代器--新的zip類型數據。zip(m, n)將返回([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3]), ([7, 8, 9], [4, 4, 4])函數
m[0], n[0] | m[1], n[1] | m[2], n[2] |
---|---|---|
[1,2,3] [2,2,2] |
[4,5,6] [3,3,3] |
[7,8,9] [4,4,4] |
zip(m, p)將返回([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3])學習
m[0], n[0] | m[1], n[1] | m[2], n[2] |
---|---|---|
[1,2,3] [2,2,2] |
[4,5,6] [3,3,3] |
[7,8,9] |
## zip()函數有2個參數 m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] n = [[2, 2, 2], [3, 3, 3], [4, 4, 4]] p = [[2, 2, 2], [3, 3, 3]] # 行與列相同 print("行與列相同:\n", list(zip(m, n))) # 行與列不一樣 print("行與列不一樣:\n", list(zip(m, p)))
輸出:code
行與列相同:
[([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3]), ([7, 8, 9], [4, 4, 4])]
行與列不一樣:
[([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3])]
對象
## zip()應用 # 矩陣相加減、點乘 m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] n = [[2, 2, 2], [3, 3, 3], [4, 4, 4]] # 矩陣點乘 print('=*'*10 + "矩陣點乘" + '=*'*10) print([x*y for a, b in zip(m, n) for x, y in zip(a, b)]) # 矩陣相加,相減雷同 print('=*'*10 + "矩陣相加,相減" + '=*'*10) print([x+y for a, b in zip(m, n) for x, y in zip(a, b)])
輸出:blog
[2, 4, 6, 12, 15, 18, 28, 32, 36]
[3, 4, 5, 7, 8, 9, 11, 12, 13]
*zip(*iterables)函數詳解 |
*zip()函數是zip()函數的逆過程,將zip對象變成原先組合前的數據。
## *zip()函數 print('=*'*10 + "*zip()函數" + '=*'*10) m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] n = [[2, 2, 2], [3, 3, 3], [4, 4, 4]] print("*zip(m, n)返回:\n", *zip(m, n)) m2, n2 = zip(*zip(m, n)) # 若相等,返回True;說明*zip爲zip的逆過程 print(m == list(m2) and n == list(n2))
輸出:
*zip(m, n)返回:
([1, 2, 3], [2, 2, 2]) ([4, 5, 6], [3, 3, 3]) ([7, 8, 9], [4, 4, 4])
True
總結 |
歡迎關注我的微信公衆號WaltSmithML或新浪微博WaltSmith,本人主要方向爲機器學習和深度學習。很是熱烈歡迎一塊兒交流學習哈,除了學習,還可免費幫忙download論文或者書籍哈==============
♥♥♥微信公衆號♥♥♥♥♥♥
♥♥♥新浪微博♥♥♥