Python-11-循环

x = 1
while x <= 100:
    print(x)
    x += 1
 
基本上, 可迭代对象是可使用for循环进行遍历的对象。
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
    print(number)
 
鉴于迭代特定范围内的数是一种常见的任务:
>>> range(0, 10)
range(0, 10)
>>> list(range(0, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
下面的程序打印数1~100:
for number in range(1,101):
print(number)
 
迭代字典
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
    print(key, 'corresponds to', d[key])
可在for循环中使用序列解包
for key, value in d.items():
    print(key, 'corresponds to', value)
 
一些迭代工具
1.并行迭代
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print(names[i], 'is', ages[i], 'years old')
函数zip:
>>> list(zip(names, ages))
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
for name, age in zip(names, ages):
print(name, 'is', age, 'years old')
函数zip可缝合任一序列,但在最短序列用完后停止缝合
>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
 
2.迭代时获取索引
如果想替换一个字符串列表中所有包含子串'xxx'的字符串,有很多种方法
一种是这样:
index = 0
for string in strings:
    if 'xxx' in string:
        strings[index] = '[censored]'
    index += 1
但使用内置函数enumerate更好:
for index, string in enumerate(strings):
    if 'xxx' in string:
        strings[index] = '[censored]'
 
3.反向迭代和排序后再迭代
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
sorted返回一个列表,而reversed像zip那样返回一个更神秘的可迭代对象。你无需关心这到底意味着什么,只管在for循环或join等方法中使用它,不会有任何问题。只是你不能对它执行索引或切片操作,也不能直接对它调用列表的方法。要执行这些操作,可先使用list对返回的对象进行转换。
要按字母表排序,可先转换为小写。为此,可将sort或sorted的key参数设置为str.lower。例如, sorted("aBc", key=str.lower)返回['a', 'B', 'c']。
 
break跳出循环
continue结束当前迭代并跳到下一次迭代开头
一般这样会让代码简洁很多:
while True:
    if(): break
 
这里在循环中添加一条else子句,它在没有调用break时才执行。(即在循环正常结束时采取某种措施)
for n in m : 
    if :
        break
else:
无论是for还是while循环都可使用continue,break和else子句
 
 
原文地址:https://www.cnblogs.com/swefii/p/10834629.html