同其它语言中的enumerate不同,在python中包含另一种情调
那就是它也是可迭代的,每一个迭代都返回两个值,一个是索引值,一个是迭代对象值
其中被enumerate的对象必须是可迭代对对象
-
ll='kinfinger'
-
for index,value in enumerate(ll):
-
print index,value
output:
-
0 k
-
1 i
-
2 n
-
3 f
-
4 i
-
5 n
-
6 g
-
7 e
-
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函数:有时候还是满有意思的:
-
info=['name','age','address']
-
value=['kin','30','SH','kinfiger@gmail.com']
-
# normal implement:
-
for i in xrange(min(len(info),len(value))):
-
print info[i],'is',value[i]
-
for name,v in zip(info ,value):
-
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.
需要注意的是它不支持的列表可以多个:
-
info=['name','age','address']
-
value=['kin','30','SH','kinfiger@gmail.com']
-
com=['1','2','3','4','5']
-
# normal implement:
-
for name,v, xx in zip(info ,value,com):
-
print name,'is',v,xx
三个列表同时处理是没有问题的,感兴趣的筒子可以是一把或是看看源代码,偶洗洗睡去了~~~~~~~~
阅读(1853) | 评论(0) | 转发(0) |