while
- break:调出循环
- continue:调到判断句
- else:当while正常结束时执行(未碰到break语句)
while 1=1:
pass
else:
pass
- pass:一个什么都不做的占位符,防止函数或者循环语句置空报错
for
for的解包
t = [(1,2),(3,4),(5,6)]
for (a,b) in t
print (a,b)
字典的解包
d = {'a'=1,'b'=2,'c'=3}
for key in d :
print (key,'>',d[key])
for (key,value) in d.items():
print (key,'>',value)
for中的range
- range(2,10,2)从2开始,到10结束(不包括10),步长为2
- range(2,-10,-1)从2开始,到-10结束(不包括10),倒序取值,需注意步长的符号选择,如果步长为1将取不到值
zip和enumerate
- zip:组合两个列表,把然后返回元组的列表,将这些序列中并排的元素配成对,当参数序列长度不同的时候,会取最短序列的长度
l1 = [1,2,3,4,5]
l2 = [6,7,8,9,10]
list(zip(l1,l2)) #[(1, 6), (2, 7), (2, 7), (3, 8), (4, 9), (5, 10)]
set(zip(l1,l2)) #{(2, 7), (5, 10), (4, 9), (3, 8), (1, 6)}
tupl(zip(l1,l2)) #((1, 6), (2, 7), (3, 8), (4, 9), (5, 10))
l1 = [1,2,3,4,5]
l2 = [6,7,8,9,10]
d = dict(zip(l1,l2)
l1 = "abcd"
list(enumerate(l1)) #[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
tuple(enumerate(l1)) #((0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'))
dict(enumerate(l1)) # {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
list(enumerate(l1)) # {(4, 'd'), (6, 'd'), (10, 'c'), (11, 'c'), (2, 'a'), (5, 'd'), (8, 'f'), (3, 'a'), (0, 's'), (9, 'c'), (1, 's'), (7, 'f'), (12, 'a')}