For 循环语句
基础知识
for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
语法:
for 循环规则:
do sth
>>> for i in "python" : #用i这个变量遍历这个字符串的每一个字符
... print i #将遍历的字符打印出来
...
p
y
t
h
o
n
>>> lst =["baidu","google","ali"]
>>> for i in lst: #用变量i遍历这个列表,将每个元素打印出来
... print i
...
baidu
ali
>>> t =tuple(lst)
>>> t
('baidu', 'google', 'ali')
>>> for i in t: #用变量i遍历元组,将每个元素打印出来
... print i
...
baidu
ali
>>> d =dict([("lang","python"),("website","baidu"),("city","beijing")])
>>> d
{'lang': 'python', 'website': 'baidu', 'city': 'beijing'}
>>> for k in d: #用变量k遍历这个字典,将每个key打印出来
... print k
...
lang
website
city
>>> for k in d: #用变量k遍历字典d
... print k,"-->",d[k] #将key值和value值打印出来
...
lang --> python
website --> baidu
city --> beijing
>>> d.items() #以列表返回可遍历的(键, 值) 元组
[('lang', 'python'), ('website', 'baidu'), ('city', 'beijing')]
>>> for k,v in d.items(): #用key value遍历d.items()的元组列表
... print k,"-->",v #取得key ,value
...
lang --> python
website --> baidu
city --> beijing
>>> for k,v in d.iteritems(): iteritems 返回的是迭代器 推荐使用这个
... print k,v
...
lang python
website baidu
city beijing
>>> d.itervalues() 返回的是迭代器
<dictionary-valueiterator object at 0x0000000002C17EA8>
>>>
判断对象是否可迭代
>>> import collections #引入标准库
>>> isinstance(321,collections.Iterable) #返回false,不可迭代
False
>>> isinstance([1,2.3],collections.Iterable) #返回true,可迭代
True
>>> l =[1,2,3,4,5,6,7,8,9]
>>> l[4:]
[5, 6, 7, 8, 9]
>>> for i in l[4:]: #遍历4以后的元素
... print i
...
5
6
7
8
9
>>> help(range) #函数可创建一个整数列表,一般用在 for 循环中
Help on built-in function range in module __builtin__: range(...)
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers #计数从 start 开始,计数到 stop 结束,但不包括 stop,step:步长,默认为1 Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements. >>> range(9)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> range(2,8)
[2, 3, 4, 5, 6, 7]
>>> range(1,9,3)
[1, 4, 7]
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(0,9,2)
[0, 2, 4, 6, 8]
>>> for i in range(0,9,2):
... print i
...
0
2
4
6
8
>>>
#! /usr/bin/env python
#coding:utf-8 aliquot =[] #创建一个空的列表 for n in range(1,100): #遍历1到100 的整数
if n %3==0: #如果被3整除
aliquot.append(n) #将n值添加到列表中 print aliquot
zip() 函数
函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
返回一个列表,这列表是以元组为元素
>>> a =[1,2,3,4,5]
>>> b =[9,8,7,6,5]
>>> c =[]
>>> for i in range(len(a)):
... c.append(a[i]+b[i])
>>> for i in range(len(a)):
... c.append(a[i]+b[i])
...
>>> c
[10, 10, 10, 10, 10]
>>> help(zip)
Help on built-in function zip in module __builtin__: zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence. >>> a
[1, 2, 3, 4, 5]
>>> b
[9, 8, 7, 6, 5]
>>> zip(a,b)
[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]
>>> c =[1,2,3]
>>> zip(c,b)
[(1, 9), (2, 8), (3, 7)]
>>> zip(a,b,c)
[(1, 9, 1), (2, 8, 2), (3, 7, 3)]
>>> d=[]
>>> for x,y in zip(a,b):
... d.append(x+y)
...
>>> d
[10, 10, 10, 10, 10]
>>> r =[(1,2),(3,4),(5,6),(7,8)]
>>> zip(*r)
[(1, 3, 5, 7), (2, 4, 6, 8)]
>>>
enumerate()函数
函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法:
enumerate(sequence, [start=0])
sequence -- 一个序列、迭代器或其他支持迭代对象
start -- 下标起始位置。
返回值: enumerate枚举对象
>>> help(enumerate)
Help on class enumerate in module __builtin__: class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| iteration. The enumerate object yields pairs containing a count (from
| start, which defaults to zero) and a value yielded by the iterable argument.
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
|
| Methods defined here:
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| next(...)
| x.next() -> the next value, or raise StopIteration
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T >>> weeks =["sun","mon","tue","web","tue","fri","sta"]
>>> for i,day in enumerate(weeks):
... print str(i)+":"+day
...
0:sun
1:mon
2:tue
3:web
4:tue
5:fri
6:sta
>>> for i in range(len(weeks)):
... print str(i)+":"+weeks[i]
...
0:sun
1:mon
2:tue
3:web
4:tue
5:fri
6:sta
>>> raw ="Do you love canglaoshi? canglaoshi is a good teacher."
>>> raw_lst =raw.split(" ")
>>> raw_lst
['Do', 'you', 'love', 'canglaoshi?', 'canglaoshi', 'is', 'a', 'good', 'teacher.']
>>> for i,w in enumerate(raw_lst):
... if w =="canglaoshi":
... raw_lst[i]="luolaoshi"
...
>>> raw_lst
['Do', 'you', 'love', 'canglaoshi?', 'luolaoshi', 'is', 'a', 'good', 'teacher.']
>>> for i,w in enumerate(raw_lst):
... if "canglaoshi" in w:
... raw_lst[i]="luolaoshi"
...
>>> raw_lst
['Do', 'you', 'love', 'luolaoshi', 'luolaoshi', 'is', 'a', 'good', 'teacher.']
>>> a =range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> s =[]
>>> for i in a:
... s.append(i*i)
...
>>> s
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> b = [i*i for i in a] #列表解析
>>> b
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> c = [i*i for i in a if i%3==0] #列表解析,加入限制条件
>>> c
[0, 9, 36, 81]
>>>
列表解析