"""
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
注释:zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。
如需展示列表,需手动 list() 转换。
"""
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b) # 打包为元组的列表
print("list(zipped):", list(zipped))
print("list(zip(a,c)):", list(zip(a,c)))# 元素个数与最短的列表一致
a1, a2 = zip(*zip(a,b)) # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
print("a1:", a1)
print("a2:", a2)
y_hat = np.array([41,62,73,84,95,36,27,58,69,80])
y_test = np.array([[11,12],
[13,14],
[15,16],
[17,18],
[19,20],
[21,22],
[23,24],
[25,26],
[27,28],
[29,30]])
for y_h, y_t in zip(y_hat, y_test):
print("y_hat,y_test,y_t[0]:", y_h, y_t, y_t[0])
y_hat,y_test,y_t[0]: 41 [11 12] 11
y_hat,y_test,y_t[0]: 62 [13 14] 13
y_hat,y_test,y_t[0]: 73 [15 16] 15
y_hat,y_test,y_t[0]: 84 [17 18] 17
y_hat,y_test,y_t[0]: 95 [19 20] 19
y_hat,y_test,y_t[0]: 36 [21 22] 21
y_hat,y_test,y_t[0]: 27 [23 24] 23
y_hat,y_test,y_t[0]: 58 [25 26] 25
y_hat,y_test,y_t[0]: 69 [27 28] 27
y_hat,y_test,y_t[0]: 80 [29 30] 29
y_hat = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
y_test = np.array([[11,21,31,41,51,61,71,81,91,101],
[12,2,3,4,5,6,7,8,9,10],
[13,2,3,4,5,6,7,8,9,10],
[14,2,3,4,5,6,7,8,9,10],
[15,2,3,4,5,6,7,8,9,10],
[16,2,3,4,5,6,7,8,9,10],
[17,2,3,4,5,6,7,8,9,10],
[18,2,3,4,5,6,7,8,9,10],
[19,2,3,4,5,6,7,8,9,10],
[10,2,3,4,5,6,7,8,9,10],
[11,2,3,4,5,6,7,8,9,10],
[12,2,3,4,5,6,7,8,9,10],
[13,2,3,4,5,6,7,8,9,10],
[14,2,3,4,5,6,7,8,9,10],
[15,2,3,4,5,6,7,8,9,10]])
for y_h, y_t in zip(y_hat, y_test):
print(y_h, y_t)
python zip()
最新推荐文章于 2023-09-15 14:56:39 发布