Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1753472
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2013-04-26 23:26:07

            同其它语言中的enumerate不同,在python中包含另一种情调
那就是它也是可迭代的,每一个迭代都返回两个值,一个是索引值,一个是迭代对象值
其中被enumerate的对象必须是可迭代对对象

点击(此处)折叠或打开

  1. ll='kinfinger'
  2. for index,value in enumerate(ll):
  3.     print index,value
output:

点击(此处)折叠或打开

  1. 0 k
  2. 1 i
  3. 2 n
  4. 3 f
  5. 4 i
  6. 5 n
  7. 6 g
  8. 7 e
  9. 8 r




usage: 
 enumerate(iterable[, start]) -> iterator for index, value of iterable


 Return an enumerate object.  iterable must be another object that supports
 iteration.  The enumerate object yields pairs containing a count (from
 start, which defaults to zero) and a value yielded by the iterable argument.
 enumerate is useful for obtaining an indexed list:
     (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
还有就是比较少见的zip函数:有时候还是满有意思的:

点击(此处)折叠或打开

  1. info=['name','age','address']
  2. value=['kin','30','SH','kinfiger@gmail.com']
  3. # normal implement:
  4. for i in xrange(min(len(info),len(value))):
  5.     print info[i],'is',value[i]
  6. for name,v in zip(info ,value):
  7.     print name,'is',v
为了实现针对两个列表信息的匹配,通常的做法是使用索引进行迭代,但是你看到,当列表的长度不一样的时候,处理还是比较繁琐的,但是
当使用了zip函数以后,你就可以对两个列表进行打包处理,当遇到两个列表中的第一个空列表是,迭代停止,是不是简单了很多?
usage: 
zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
    
    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

需要注意的是它不支持的列表可以多个:

点击(此处)折叠或打开

  1. info=['name','age','address']
  2. value=['kin','30','SH','kinfiger@gmail.com']
  3. com=['1','2','3','4','5']
  4. # normal implement:
  5. for name,v, xx in zip(info ,value,com):
  6.     print name,'is',v,xx
三个列表同时处理是没有问题的,感兴趣的筒子可以是一把或是看看源代码,偶洗洗睡去了~~~~~~~~



阅读(1791) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~