1. 程式人生 > >python迴圈之for迴圈

python迴圈之for迴圈

python還有個迴圈是for迴圈。

for迴圈一般用於遍歷元組、集合、列表這種資料型別裡面的所有元素。(字典只會遍歷索引)

#簡單的for迴圈結構(不同於while迴圈容易變成無限迴圈,for迴圈遍歷完或中止便會結束執行)#
a = ('ppap','hello,world','phone')
for b in a:
    print (b)

#如果for迴圈的資料同時有不同的資料型別(比如元組、集合)也可以同時遍歷不同資料的內部元素。#
a = [('ppap','hello,world','phone'),['hello','zero','plane'],{'1':'one','2':'two','3':'three'},{1,2,3,4,5}]
for b in a:
    for c in b:
        print (c)

#for迴圈遍歷後列印的一般都是每一個元素一行,我們可以使用end函式來使它變成一列#
a = [('ppap','hello,world','phone'),['hello','zero','plane'],{'1':'one','2':'two','3':'three'},{1,2,3,4,5}]
for b in a:
    for c in b:
        print (c,end='')

#為了方便區分元素可以在end函式裡面加一個分隔符號#
a = [('ppap','hello,world','phone'),['hello','zero','plane'],{'1':'one','2':'two','3':'three'},{1,2,3,4,5}]
for b in a:
    for c in b:
        print (c,end=';')

#如果想中止於某個元素前,可以在for迴圈中加入break函式#
a = ['ppap','hello,world','phone','hello','zero']
for b in a:
    if b == 'phone':
        break
    print (b,end=';')

#如果想中止於某個元素後,就將break函式加在最後面#
a = ['ppap','hello,world','phone','hello','zero']
for b in a:
    print (b,end=';')
    if b == 'phone':
        break

#如果遍歷時想跳過某個元素,將break換為continue函式即可#
a = ['ppap','hello,world','phone','hello','zero']
for b in a:
    if b == 'phone':
        continue
    print (b,end=';')

#如果使用的是兩層for迴圈,這時候在最後一層for迴圈裡使用break,迴圈只會終止當前迴圈,最外面的迴圈並不會終止(這裡比較容易出bug)#
a = [['ppap','hello','world','where','apple'],('phone','kille','zero')]
for b in a:
    for c in b:
        if c == 'world':
            break
        print (c,end=';')

#如果想在終止內部迴圈的同時也中止外部迴圈只需要在外部迴圈最下方加一個if break語句即可#
a = [['ppap','hello','world','where','apple'],('phone','kille','zero')]
for b in a:
    for c in b:
        if c == 'world':
            break
        print (c,end=';')
    if c == 'world':
        break

 

for不僅可以遍歷元素,還可以和range函式結合生成元素。

#生成數字串(range中最後一個數字不會出現,左邊那個數字為起始數)#
for a in range(20,30):
    print (a,end='|')

#也可以生成遞增和遞減的等差數列#
for a in range(20,31,2):
    print (a,end='|')

for a in range(60,49,-2):
    print (a,end='|')

#也可以等差取出資料裡的元素#
a = [11,12,13,14,15,16,17,18,19,20,]
for b in range(0,len(a),2):
    print(a[b],end='|')