Python基礎(三):循環

Python循環

程序一般是順序執行,if else 也是順序執行的;而循環(cycle)是控制程序執行流程的;

循環是程序的主要過程之一,對於列表的訪問,數列的計算都有很好的用途。在迭代過程中很有用,還有就是等比,等差數列和一些不是很容易求的數列都可以通過循環來進行求解。

Python循環只有兩種while , for

# while 循環
count = 0
while count < 10:
    print "the count is ", count
    count += 1
print '循環結束'

while....else滿足執行裏面的,不滿足執行else語句塊

for循環在迭代讀取方面很好用:

for item in iterable:
    do something 

例子:for循環只要兩句,while循環卻要四句

# 遍歷字符串
a = 'python'
print a[0:2]
# 使用while遍歷a
i = 0
while i < len(a):
    print a[i]
    i += 1
#使用range()判斷是不是在範圍
k = 0
while k in range(len(a)):
    print a[k]
    k += 1
# 使用for循環遍歷a
for i in a:
    print i
#使用下表讀取:
for i in range(len(a)):
    print a[i]

for循環對字典的讀取

字典是無序的,所以for讀取時候就不能通過下標進行讀取,而是通過name值讀取對應的value

#字典先找到keys()值,然後再通過key去找value
city = {'張三':['a','b','c'],'李四':[1,2,3,4,5]}
for name in city.keys():
    for c in city[name]:
        print name, c

enumerate()函數,自動生成下表

# for 下標 ,值 in enumerate()
letter = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(letter):
    print value, 'is', index
輸出:
a is 0
b is 1
c is 2
d is 3
e is 4

zip()

同時操作兩個列表zip()函數:裏面參數是可迭代的對象:

如果各個迭代器的元素個數不一致,則按照最小的返回

list1 = ['hello', 'world', 'yes']
list2 = [1, 2, 3]
print zip(list1, list2)
print zip(list2, list1)
輸出:
[('hello', 1), ('world', 2), ('yes', 3)]
[(1, 'hello'), (2, 'world'), (3, 'yes')]

不一致情況:

list1中去掉一個元素
list1 = ['hello', 'world']
list2 = [1, 2, 3]
print zip(list1, list2)
print zip(list2, list1)
輸出:
[('hello', 1), ('world', 2)]
[(1, 'hello'), (2, 'world')]

在字典中的情況:

list1 = (1, 2, 3)
dict1 = {'num1': 'one', 'num2': 'two', 'num1': 'three'}
# .keys() 獲取字典中所有的鍵值 .values()獲取字典中所有的值
print dict1.keys()
print dict1.values()
print zip(list1, dict1)

list2 = [1, 2]
# append 操作是無返回值的,所以打印是None
print list2.append(3)

zip()反向操作,把組合的數在反轉成原來的列表形式:

# 反向操作 zip(*xxx)
num1 = [2, 4, 6, 8]
num2 = [1, 3, 5, 7]
result = zip(num1, num2)
print result
result.append((10, 19))
print result
print zip(* result)
#輸出結果:
[(2, 1), (4, 3), (6, 5), (8, 7)]
[(2, 1), (4, 3), (6, 5), (8, 7), (10, 19)]
[(2, 4, 6, 8, 10), (1, 3, 5, 7, 19)]

循環嵌套

for  a in range(4):
    print '------------'
    for b in range(3):
        print b,
    print ''

推導式,列表的解析式:

速度比for循環更高效推導式代碼少,運行速度快

# 把大寫英文變成小寫
print [x.lower() for x in list('ABCDEF')]
print [x.upper() for x in 'adbcef']
# 輸出:
['a', 'b', 'c', 'd', 'e', 'f']
['A', 'D', 'B', 'C', 'E', 'F']
# 字典的推導式
print {i: i+1 for i in range(4)}
print {i: j for i, j in zip(range(3), 'abc')}
輸出:
{0: 1, 1: 2, 2: 3, 3: 4}
{0: 'a', 1: 'b', 2: 'c'}

字典的推導式:因爲鍵值對存在,所以有所不同

e = {key:value for key ,value in list}

break,continue,pass

都是隻對當前一層循環起作用;

示例:

#正常不帶break和pass的語句:
for i in range(4):
    print i
    for j in range(5):
        # if j == 2:# break #continue
        print j,
    print
#輸出:
0
0 1 2 3 4
1
0 1 2 3 4
2
0 1 2 3 4
3
0 1 2 3 4

continue 跳過這一次循環:

# continue 跳過本次循環
for i in range(4):
    print i
    for j in range(5):
        if j == 2:
            continue
        print j,
    print
輸出:
0  #第一層循環輸出
0 1 3 4 #第二層循環輸出 ,其中第二層循環的j==2時的布輸出了
1
0 1 3 4
2
0 1 3 4
3
0 1 3 4

break 跳出整個循環;

# continue 跳過本次循環
for i in range(4):
    print i
    for j in range(5):
        if j == 2:
            break #break
        print j,
    print
#輸出:
0
0 1
1
0 1
2
0 1
3
0 1

pass 是空語句保持完整性:

例子:

for i in range(10):
    pass # 保持代碼的完整性

for … else: else是在for循環正常執行完(不是通過break語句而中斷的)會執行的語句:

# 13、使用while輸出1-100內的質數 ,類似於 2,3,5,7,11,13....
x = 1
while x < 100:
    tmp = x // 2
    while tmp > 1:
        if x % tmp == 0:
            break
        else:
            tmp -= 1
    else:  # 這個else是跟while關聯的,這樣就當while都循環完成了以後就會執行else,用這個可以巧妙的進行打印質數,當所有
        print x,
    x += 1
i = 0
while 8*(2**i) < 8848130:
    i += 1
else:
    print i

range()

函數前開後閉;例子:

print range(10)
print range(0,10,1)
print range(10,-1,-5)
print range(10,2) # 默認步長是加一,這個裏面沒有辦法所以輸出爲空
print range(-3,-1)
輸出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 5, 0]
[]
[-3, -2]
發佈了33 篇原創文章 · 獲贊 20 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章