python之循环,遍历,嵌套

遍历:将文件,字符串,列表,元组,字典等里面的数据一一列举出来

字符串遍历:

num="hello,world"        #创建字符串并赋值

for i in num:        #对于字符串的for循环遍历,变量I表示该字符串中任意一个元素,i只为一个变量,可以随意起名

        print (i)            #输出的是该字符串的每个字符,输出一个字符换一行

或者使用while遍历:

num="hello,world"        #创建字符串并赋值

i=0        #创建变量i并赋予0

while i<len(num):        #while后面接的是条件

        print(num[i]

        i+=1

列表的遍历:(注:对于列表而言,其遍历出来的元素和在列表中的数据类型一致)

nums=[11,22,33,44,55,66]        #创建列表并赋值,该列表中的元素都为整型,那么遍历出来后也都为整型

for    i    in     nums:

    print(i)                            #输出的是每一个元素,即为:11  22  33  44  55 66 

使用while遍历列表:

nums=[11,22,33,44,55,66]

i=0

while    i<len(nums):

        print(i)

        i=i+1

字典嵌套到列表中,遍历列表

nums=[{"name":"xiaoming","age":19},{"name":"xiaoli","age":18}]

i=0

while i<len(nums):

        print(nums[i])                    

        i+=1

得到的结果为:{'name': 'xiaoming', 'age': 19}    {'name': 'xiaoli', 'age': 18} 列表中的每个字典

使用for循环遍历

nums=[{"name":"xiaoming","age":19},{"name":"xiaoli","age":18}]

for i in nums:

        print(i)            #得到的结果也是一样的

元组的遍历

nums=("abc","defo")

for i in nums:

        print(i)        #输出的是该元组里面的字符串"abc""defo"

列表中嵌套元组

nums=[(123,456),("abc","defo")]

for i in nums:

        print(i)        #输出的是该列表中所有的元组,即为:(123,456)    ( "abc","defo")

for-else语句(python独有的特性)

nums=[11,22,33,44,55]

for i in nums:

        print(i)

else:

        print("=======" )      #使用for-else结构,即将for循环遍历完成之后执行else语句的内容,即下图所示

这里写图片描述

nums=[11,22,33,44,55]

for i in nums:       

        print(i)

        break

else:       

        print("=======" )      #使用for-else结构,如果for循环中有break,那么程序会如果执行了for循环,那么就不会继续执行else的内容

猜你喜欢

转载自blog.csdn.net/qq_39353923/article/details/82149136
今日推荐