# 举例讲解如何在python编程中进行迭代和遍历

1.文件操作

>>> f=open(‘hello.py’)
‘#!/usr/bin/python2.5\n’
‘print “hello.word!”\n’
‘\n’

>>> for i in open(‘hello.py’):
… print(i)

#!/usr/bin/python2.5
print “hello.word!”

… print i

#!/usr/bin/python2.5
print “hello.word!”

2 for循环

>>> for i in range(5):
… print(i)

>>> l=[0,1,2,3,4]
>>> i=iter(l)
>>> i.next()
0
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
4
>>> i.next()

traceback (most recent call last):
file “”, line 1, in
stopiteration

3.列表解析:

>>> l=[x+10 for x in range(10)]
>>> l

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
python会在解释器里对range(10)进行迭代，依次把列表里的内容取出来，赋值给最左边的x,然后执行x+10的操作，

>>> res=[]
>>> for x in range(10):
… res.append(x+10)

>>> res
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

1.通过序列取元素的方法进行遍历

root@10.1.6.200:python# vim 3.py

#!/usr/bin/python2.5
for i in ‘hello’: #序列里的字符串
print i,
y = [1,2,3,4,5,6] #列表
for i in y:
print i,

root@10.1.6.200:python# python 3.py

h e l l o 1 2 3 4 5 6

2.通过序列本身偏移指数(索引)的方法进行遍历

root@10.1.6.200:python# vim 3.py

#!/usr/bin/python2.5
x=’hello’
for i in range(len(x)):
print x[i]
y = [1,2,3,4,5,6]
for i in range(len(y)):
print y[i],

root@10.1.6.200:python# python 3.py

h e l l o 1 2 3 4 5 6

1.先取字典key,在取索引的值

root@10.1.6.200:python# vim 5.py

#!/usr/bin/python2.5
z = {1:’a’,2:’b’,3:’c’}
for i in z:
print z[i]

root@10.1.6.200:python# python 5.py

a
b
c

2.通过字典items方法,获取所有键值对,在利用元组拆分的方法获得对应值.

root@10.1.6.200:python# cat 5.py

#!/usr/bin/python2.5
z = {1:’a’,2:’b’,3:’c’}
print z.items()
for m,n in z.items():
print m,n

root@10.1.6.200:python# python 5.py

[(1, ‘a’), (2, ‘b’), (3, ‘c’)]
1 a
2 b
3 c

Posted in 未分类