python入门七(迭代)【9-1 python之迭代】

9-1 python之迭代

什么是迭代

在Python中,如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们成为迭代(Iteration)。

因为 Python 的 for循环不仅可以用在list或tuple上,还可以作用在其他任何可迭代对象上。

因此,迭代操作就是对于一个集合,无论该集合是有序还是无序,我们用 for 循环总是可以依次取出集合的每一个元素。

注意: 集合是指包含一组元素的数据结构,我们已经介绍的包括:
1. 有序集合:list,tuple,str和unicode;
2. 无序集合:set
3. 无序集合并且具有 key-value 对:dict

任务

请用for循环迭代数列 1-100 并打印出7的倍数。

1 for i in range(1,101):
2     if i % 7 ==0:
3         print i

索引迭代

Python中,迭代永远是取出元素本身,而非元素的索引

对于有序集合,元素确实是有索引的。有的时候,我们确实想在 for 循环中拿到索引,怎么办?

方法是使用 enumerate() 函数

>>> L = ['Adam', 'Lisa', 'Bart', 'Paul']
>>> for index, name in enumerate(L):
...     print index, '-', name
... 
0 - Adam
1 - Lisa
2 - Bart
3 - Paul

使用 enumerate() 函数,我们可以在for循环中同时绑定索引index和元素name。但是,这不是 enumerate() 的特殊语法。实际上,enumerate() 函数把:

['Adam', 'Lisa', 'Bart', 'Paul']

变成了类似:

[(0, 'Adam'), (1, 'Lisa'), (2, 'Bart'), (3, 'Paul')]

因此,迭代的每一个元素实际上是一个tuple:

1 for t in enumerate(L):
2     index = t[0]
3     name = t[1]
4     print index, '-', name

可见,索引迭代也不是真的按索引访问,而是由 enumerate() 函数自动把每个元素变成 (index, element) 这样的tuple,再迭代,就同时获得了索引和元素本身。

猜你喜欢

转载自www.cnblogs.com/ucasljq/p/11597772.html