python --条件、循环和其他语句(二)

1.  while 循环

比如求1到100总和 :

s = 0
i=0
while i <= 100:
    s=s+i
    i=i+1
print(s)

2. for 循环

while语句非常灵活,可用于在条件为真时反复执行代码块。这在通常情况下很好,但有时
候你可能想根据需要进行定制。一种这样的需求是为序列(或其他可迭代对象)中每个元素执行
代码块。基本上,可迭代对象是可使用for循环进行遍历的对象。

例如:

    

words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
    print(word)

 

提示 只要能够使用for循环,就不要使用while循环,因为for 循环更加可读

3. 迭代字典:

  要遍历字典的所有关键字,可像遍历序列那样使用普通的for语句。

 

d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
     print(key, 'corresponds to', d[key])

迭代工具:

并行迭代:

names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]

names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
a = zip(names,ages)
for i,j in a:
    print(i,j)

内置函数zip 可以实现两个列表之间的一一对应

迭代时获取索引

需求: 当碰到a时候替换为b

a = 'abcdeab'
a=list(a)
print(len(a))
for i in range(0,len(a)):
    if a[i] == 'a':
        a[i]='b'
print(a) 

还可以用enumerate内置函数

a = 'abcdeab'
for i,j in enumerate(a):
    if j=='a':
        j='b'
    print(j)

 

posted on 2018-09-11 17:28  道森_daodao  阅读(147)  评论(0)    收藏  举报

导航