Python3-筆記-C-002-函數-zip
阿新 • • 發佈:2017-10-25
sof ict pytho ros -s -c zip() 新的 可叠代對象
def testzip():
# zip是將每個可叠代對象的對應位置元素打包成一個tuple組
# 操作符*與zip函數配合可以實現與zip相反的功能, 即將合並的序列拆成多個tuple
# 新的序列的長度以參數中最短的序列為準
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = list(zip(x, y, z)) # <class ‘list‘>: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = list(zip(x, y)) # <class ‘list‘>: [(1, 4), (2, 5), (3, 6)]
x = [1, 2, 3]
x = list(zip(x)) # <class ‘list‘>: [(1,), (2,), (3,)]
x = list(zip()) # <class ‘list‘>: []
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = list(zip(x, y, z)) # <class ‘list‘>: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
u = list(zip(*xyz)) # <class ‘list‘>: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
x = [1, 2, 3]
r = list(zip(*[x] * 3)) # <class ‘list‘>: [(1, 1, 1), (2, 2, 2), (3, 3, 3)]
# 使用zip反轉字典
m = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3, ‘d‘: 4}
m2 = dict(zip(m.values(), m.keys()))
Python3-筆記-C-002-函數-zip