Python那些事

zip(*iterables)函数详解

2018-03-18  本文已影响164人  听风1996

zip(*iterables)函数详解

zip()函数的定义

## 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()函数有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)))

输出

行与列相同:
[([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)])

输出:

=*=*=*=*=*=*=*=*=*=*矩阵点乘=*=*=*=*=*=*=*=*=*=*
[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(m2,n2)
print(m == list(m2) and n == list(n2))

输出:

=*=*=*=*=*=*=*=*=*=**zip()函数=*=*=*=*=*=*=*=*=*=*
*zip(m, n)返回:
 ([1, 2, 3], [2, 2, 2]) ([4, 5, 6], [3, 3, 3]) ([7, 8, 9], [4, 4, 4])
([1, 2, 3], [4, 5, 6], [7, 8, 9]) ([2, 2, 2], [3, 3, 3], [4, 4, 4])
True
上一篇下一篇

猜你喜欢

热点阅读