Python zip 函數

zip的輸入是positional auguments, 而且要求每個augument都是可以迭代的,例如list, tuple等。zip會把每個位置的元素拿出來拼成tuple,最後成爲一個可以迭代每個tuple的對象。

The single star * unpacks the sequence/collection into positional arguments

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中爲了減少內存,zip() 返回的是一個對象。如需展示列表,需手動 list() 轉換。

更重要的是看一些例子,下面例子都是針對Python3

a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)     # 打包爲元組迭代的object
print(list(zipped)) #[(1, 4), (2, 5), (3, 6)],Python3中一定需要list才能print,否則就是print object
print(list(zipped)) #[],zipped在被List後已經變成了空object
print(list(zip(a,c))) #[(1, 4), (2, 5), (3, 6)],元素個數與最短的列表一致

#The single star * unpacks the sequence/collection into positional arguments
print(list(zip(*zip(a,b)))) #[(1, 2, 3), (4, 5, 6)],實現了壓縮又壓回來的效果

x = [[1,2,3],[4,5,6]]
print(list(zip(*x))) #[(1, 4), (2, 5), (3, 6)],實現了矩陣轉置的效果
print(list(zip(*zip(*x)))) #[(1, 2, 3), (4, 5, 6)],實現了轉置再轉回來的效果

dic = { 'c': 10, 'd': 15 }
print(*dic) #c d
#print(**dic) #python3中不再支持對dict這麼拿values,會報錯

#print(list(zip(1,2,3))) #會拋錯, zip argument #1 must support iteration

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章