while,for 循环(range,zip,map,enumerate简介)

while:提供了编写通用循环的一种方法

while <test>:
    <statement1>
else:
    <statement2>

break, continue

while <test1>:
    <statements1>
    if <test2>: break    #exit loop now, skip else
    if <test3>: continue    #GO to top of loop now, to test1
else:
    <statements2>    #Run if we didn't hit a 'break'

pass: 无运算的占位符。

通常用于为复合语句编写一个空的主体,大概意思是以后会填上。也可用'...'来代替pass

def func1():
    pass

def func1():
    ...

 

for:通用的序列迭代器:用它来遍历序列对象内的元素,并对每一个元素执行一个代码块

for <target> in <object>:    # assign object items to target
    <statements>
else:
    <statements>    # if we didn't hit a 'break'

for 循环甚至可以应用在一些根本不是序列的对象上,对于文件和字典也有效。

嵌套for循环:

>>> items = ['aaa', 111, (4,5), 2.01]
>>> tests = [(4,5), 3.14]
>>> for key in tests:
	for item in items:
		if item == key:
			print(key, 'was found')
			break
	else:
		print(key, 'not found')

		
(4, 5) was found
3.14 not found
>>> for key in tests:
	if key in items:
		print(key, 'was found')
	else:
		print(key, 'not found')

		
(4, 5) was found
3.14 not found
>>> seq1 = 'spam'
>>> seq2 = 'scam'
>>> res = []
>>> for x in seq1:
	if x in seq2:
		res.append(x)

		
>>> res
['s', 'a', 'm']

文件扫描:

for line in open('text.txt'):    #iterators: best text input mode
    print(line)    

 

编写循环的技巧

一般而言,for比while容易写,执行也更快。

python提供内置函数,在for循环内定制迭代:

range

>>> range(5),range(3,6),range(1,10,2)    # return range object
(range(0, 5), range(3, 6), range(1, 10, 2))
>>> list(range(5)),list(range(3,6)),list(range(1,10,2))    #change range obj to list obj
([0, 1, 2, 3, 4], [3, 4, 5], [1, 3, 5, 7, 9])
>>> list(range(5,-5,-1))    # thisrd para, step
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
>>> for i in range(3):
	print(i, 'new')

	
0 new
1 new
2 new
>>> s ='abcdefghijk'
>>> list(range(0,len(s),2))
[0, 2, 4, 6, 8, 10]
>>> for i in range(0,len(s),2):print(s[i],end=' ')    #use range

a c e g i k 
>>> for c in s[::2]:print(c, end=' ')    #use slice

a c e g i k 

# 如上,range的优点是没有复制字符串,对于较大的字符串,这会节省内存
# all add 1
# 错误演示
>>> ll = [1,2,3,4,5]
>>> for x in ll:
	x += 1

	
>>> ll
[1, 2, 3, 4, 5]
>>> x
6

# 正确方法
>>> for i in range(len(ll)):
	ll[i] += 1

	
>>> ll
[2, 3, 4, 5, 6]
>>> 
# 列表解析,不在原处修改,生成新的列表再赋值给ll
>>> ll = [x+1 for x in ll]
>>> ll
[3, 4, 5, 6, 7]

 

并行遍历: zip和map

>>> l1 = [1,2,3,4]
>>> l2 = [5,6,7,8]
>>> zip(l1,l2)
<zip object at 0x000001C1649B6788>
>>> list(zip(l1,l2))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> for (x,y) in zip(l1,l2):print(x,y,'--',x+y)

1 5 -- 6
2 6 -- 8
3 7 -- 10
4 8 -- 12

zip返回zip迭代对象,可以包在list调用中显示结果

zip可以接受任何类型的序列参数(任何可迭代对象,包括文件),可以有两个以上的序列

当参数长度不同时,以最短的序列长度截断

>>> s1 = 'abc'
>>> s2 = 'abcd'
>>> s3 = 'abcde'
>>> list(zip(s1,s2,s3))
[('a', 'a', 'a'), ('b', 'b', 'b'), ('c', 'c', 'c')]

使用zip构造字典:

>>> keys = ['spam','eggs','toast']
>>> l2
[5, 6, 7, 8]
>>> dd = dict(zip(keys,l2))
>>> dd
{'spam': 5, 'eggs': 6, 'toast': 7}

map(后文详解)

map会带一个函数,以及一个或多个的序列参数,然后从序列中取出的并行元素调用函数的结果收集起来

>>> list(map(ord,'spam'))
[115, 112, 97, 109]

产生偏移和元素:enumerate

enumerate函数返回一个生成器对象,这个对象有一个__next__方法,由下一个内置函数调用它,并且循环中每次迭代的时候它会返回一个(index, value)的元组

>>> s = 'bag'
>>> for (i, v) in enumerate(s):print(i, v)

0 b
1 a
2 g
>>> ee = enumerate(s)
>>> next(ee)
(0, 'b')
>>> next(ee)
(1, 'a')
>>> next(ee)
(2, 'g')
>>> next(ee)    # 超出
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    next(ee)
StopIteration
>>> [x*i for (i,x) in enumerate(s)]
['', 'a', 'gg']

Learning Python, Fourth Edition, by Mark Lutz.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值