python zip() 函数使用

转载来源:http://www.cnblogs.com/frydsh/archive/2012/07/10/2585370.html

问题引入:

lmbda = sum(x*y for x, y in zip(range(8), num_years))/sum(num_years)

当我看到zip(range(8 ) , num_years),的时候,我的第一反应,这是不是在处理压缩包的数据呀?!但是这又貌似没有路径,也没有读写操作。

 

 那就直接尝试一下看代码的输出

 

num_years = [2,4,5,15,5,3,1,1]

for x, y in zip(range(8), num_years):
    print(x,y)
    

输出结果:

 

 

0 2
1 4
2 5
3 15
4 5
5 3
6 1
7 1

 

 

对比两个代码
all={"jack":2001,"beginman":2003,"sony":2005,"pcky":2000}
for i in all.keys():
     print i,all[i]
 
输出:
sony 2005
pcky 2000
jack 2001
beginman 2003

 

 

 

 

 

 

发现它们之间的区别么?

最显而易见的是:第一种简洁、灵活、而且能顺序输入。

然而什么是zip()  函数呢?!

不懂就多用help查看

 

help(zip)
Help on class zip in module builtins:

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |  
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

 

 

 


大概意思就是:

 

 

 

 

定义:zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同

 

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz
输出:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]


从这个结果可以看出zip函数的基本运作方式。

 

 

 

 

 
x = [1, 2, 3] y = [4, 5, 6, 7] xy = zip(x, y) print xy 输出: [(1, 4), (2, 5), (3, 6)] 
 

 

 

 

从这个结果可以看出zip函数的长度处理方式。

 

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
u = zip(*xyz)
print u
输出:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

 

一般认为这是一个unzip的过程,它的运行机制是这样的:

在运行zip(*xyz)之前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

那么,zip(*xyz) 等价于 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))

所以,运行结果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

注:在函数调用中使用*list/tuple的方式表示将list/tuple分开,作为位置参数传递给对应函数(前提是对应函数支持不定个数的位置参数)

 

x = [1, 2, 3]
r = zip(* [x] * 3)
print r
输出:
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

 

 

 

它的运行机制是这样的:

[x]生成一个列表的列表,它只有一个元素x

[x] * 3生成一个列表的列表,它有3个元素,[x, x, x]

zip(* [x] * 3)的意思就明确了,zip(x, x, x)

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值