python循环之for循环

版权声明:此博客内容为本人学习笔记,转载请标明出处!本人所有文章仅发布于CSDN! https://blog.csdn.net/weixin_40457797/article/details/83069891

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='|')

猜你喜欢

转载自blog.csdn.net/weixin_40457797/article/details/83069891