python学习之”迭代从入门到精通“

在开发的过程中,假如给你一个list或者tuple,我们可以通过for循环来遍历这个list或者tuple,这种遍历我们成为迭代(Iteration)。在Python中,迭代是通过for ... in来完成的,而很多语言比如C或者Java,迭代list是通过下标完成的,比如Java代码

: 1 for(int x = 0;x<n;x++) 2 { 3 a[i] = i; 4 } 

可以看出,Python的for循环抽象程度要高于Java的for循环,因为Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict也可以迭代。

1. 列表(List)的迭代:

1 >>> list1 = []
2 >>> n = 10
3 >>> for i in range(n):
4 ...     list1.append(i)
5 ... 
6 >>> list1
7 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8 >>> 

2. 元组tuple的迭代:

3. 字典(Dict)的迭代:

 1 >>> #字典的迭代
 2 >>> dict1 = {'a':1,'b':2,'c':3,'d':4}
 3 >>> dict1
 4 {'a': 1, 'c': 3, 'b': 2, 'd': 4}
 5 >>> for key in dict1:
 6 ...     print key
 7 ... 
 8 a
 9 c
10 b
11 d
12 >>> 

因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.itervalues(),如果要同时迭代keyvalue,可以用for k, v in d.iteritems()

1 def get_tp_type_name(value):
2     if value is None:
3         return ""
4 
5     for k, v in TP_TYPE_CHOICE:
6         if k == value:
7             return v

4. 任意字符串的迭代:

 1 >>> for ch in "abcadadadwf":
 2 ...     print ch
 3 ... 
 4 a
 5 b
 6 c
 7 a
 8 d
 9 a
10 d
11 a
12 d
13 w
14 f
15 >>> 

所以,当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:

 1 >>> from collections import Iterable
 2 >>> isinstance('abudauidua',Iterable)#str是否可以迭代
 3 True
 4 >>> isinstance(dict1,Iterable)#dict1是否可以迭代
 5 True
 6 >>> isinstance(list1,Iterable)#list1是否可以迭代
 7 True
 8 >>> isinstance(tuple1,Iterable)#list1是否可以迭代
 9 True
10 >>> isinstance(123456789,Iterable)#全数字是否可以迭代
11 False
12 >>> 

如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:

1 >>> for i ,value in enumerate(['a','b','c','d']):
2 ...     print i ,value
3 ... 
4 0 a
5 1 b
6 2 c
7 3 d
8 >>> 

像这种在一个迭代中一次引用了两个变量在python中是很常见的一件事情,因此不应太奇怪,例如:起初我看到这样的循环输出语句也是感到很奇怪,慢慢就习惯了。

1 >>> for x,y in [(1,2),(3,4),(5,6)]:
2 ...     print x,y
3 ... 
4 1 2
5 3 4
6 5 6
原文地址:https://www.cnblogs.com/blogofwyl/p/4286738.html