前言 |
zip(*iterables)函数详解 |
传入参数:
元组、列表、字典等迭代器。python
当zip()函数中只有一个参数时
zip(iterable)
从iterable中依次取一个元组,组成一个元组。git
示例:github
## 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(a,b)
zip()函数分别从a和b依次各取出一个元素组成元组,再将依次组成的元组组合成一个新的迭代器--新的zip类型数据。zip(m, n)将返回([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3]), ([7, 8, 9], [4, 4, 4])函数
m[0], n[0] | m[1], n[1] | m[2], n[2] |
---|---|---|
[1,2,3] [2,2,2] |
[4,5,6] [3,3,3] |
[7,8,9] [4,4,4] |
zip(m, p)将返回([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3])学习
m[0], n[0] | m[1], n[1] | m[2], n[2] |
---|---|---|
[1,2,3] [2,2,2] |
[4,5,6] [3,3,3] |
[7,8,9] |
## 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)))
输出:code
行与列相同:
[([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)])
输出:blog
[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(m == list(m2) and n == list(n2))
输出:
*zip(m, n)返回:
([1, 2, 3], [2, 2, 2]) ([4, 5, 6], [3, 3, 3]) ([7, 8, 9], [4, 4, 4])
True
总结 |
欢迎关注我的微信公众号WaltSmithML或新浪微博WaltSmith,本人主要方向为机器学习和深度学习。很是热烈欢迎一块儿交流学习哈,除了学习,还可免费帮忙download论文或者书籍哈==============
♥♥♥微信公众号♥♥♥♥♥♥
♥♥♥新浪微博♥♥♥