zip( ) 函数
-
zip( ) 的作用
b = ["red", "green", "blue"] c = ["leopard", "cheetah", "jaguar"] for x,y in zip(b,c): print(x, y)
red leopard green cheetah blue jaguar
-
zip( ) 转list[]
b = ["red", "green", "blue"] c = ["leopard", "cheetah", "jaguar"] new_list = list(zip(b, c))
输出:
[('red', 'leopard'), ('green', 'cheetah'), ('blue', 'jaguar')]
--若想转元组,输出list索引即可 new_list[0]
输出:
('red', 'leopard')
-
zip( ) 转dict{ }
b = ["red", "green", "blue"] f = ["strawberry", "kiwi", "blueberry"] print(dict(zip(b, f)))
输出:
{'red': 'strawberry', 'green': 'kiwi', 'blue': 'blueberry'}
-
解压列表
a = [1, 2, 3] b = [4, 5, 6] zipped = zip(a, b) print(list(zipped)) a2, b2 = zip(*zip(a, b)) 解压结果: [1, 2, 3] [4, 5, 6]
- zip( )与for 循环组合
m = ["mind", "mouse", "mini"] n = ["norm", "night", "necklace"] [print(a, b) for a, b in zip(m, n)] 输出: mind norm mouse night mini necklace