Python高级特性——迭代(Iteration)

1、给定一个集合list或者tuple,可以通过for …… in ……的语法来实现循环遍历,这个循环我们就叫做迭代

迭代list:

>>> m = ['haha','hehe','heihei','gaga']
>>> for li in m:
...     print(li)
...
haha
hehe
heihei
gaga

迭代字符串:

>>> n = 'abcdefg'
>>> for str in n :
...     print(str)
...
a
b
c
d
e
f
g

迭代dict,迭代key

>>> l = {'name':'wuchong','age':15}
>>> for dic in l:
...     print(dic)
...
name
age

迭代value:

>>> for dic in l.values():
...     print(dic)
...
wuchong
15

同时迭代key、value:

>>> for key,value in l.items():
...     print(key,value)
...
name wuchong
age 15

Python中,只要是可迭代对象,都可以迭代。

那么,如何判断一个对象是不是可迭代对象呢?方法是通过collections中的Iterable类型判断。

>>> from collections import Iterable
>>> isinstance('123',Iterable)
True
>>> isinstance([1,2,3],Iterable)
True
>>> isinstance(123,Iterable)
False

可知,整数类型不是可迭代类型。

通过Python内置的enumerate函数可以把一个list变成索引-元素对的形式:

>>> m
['haha', 'hehe', 'heihei', 'gaga']
>>> for dx,value in enumerate(m):
...     print(dx,value)
...
0 haha
1 hehe
2 heihei
3 gaga

练习:使用迭代从一个list中查询最大值和最小值,如果list为None,返回[None,None],并返回一个tuple

>>> def find(l):
...     if l==[]:
...             return (None,None)
...     else:
...             min  = max  = l[0]
...             for i in l:
...                     if i<min :
...                             min = i
...                     if i>max:
...                             max = i
...             return (min,max)
>>> l=[3,6,4,8,1,0]
>>> find(l)
(0, 8)
>>> l=[]
>>> find(l)
(None, None)
原文地址:https://www.cnblogs.com/hiwuchong/p/8052818.html