pyDay7

内容来自雪峰的官方网站

1、如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)

 

2、只要是可迭代对象,无论有无下标,都可以迭代。例如:dict、字符串

 

3、那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:

>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False

 

4、Python内置的 enumerate函数 可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:

>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B
2 C
>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9

 

5、列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式

例如生成[1x1, 2x2, 3x3, ..., 10x10]:

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

6、list:[1, 2, 3]、tuple:(1, 2, 3)、dict:{1: 1, 2: 2, 3: 3}、set:set([1, 2, 3])

 

7、dict(key-value存储方式)的几种迭代示例

>>> dict = {'migo': 18, 'lucy': 17, 'jack': 22}
>>> for x in dict:
...     print(x)
...
lucy
migo
jack
>>> for x in dict.values():
...     print(x)
...
17
18
22
>>> for x, y in dict.items():
...     print(x , y)
...
lucy 17
migo 18
jack 22

 

posted @ 2017-02-16 14:52  xkfx  阅读(177)  评论(0)    收藏  举报