python基础教程: for 循环用法
1.for … in 循环
循环,遍历,迭代 都是指把容器中的数据一个一个获取出来
lst = [1,2,3,4,5]
i = 0
while i<len(lst):
print(lst[i])
i+=1
# 无法用while 它的索引下标获取集合其中的值;
setvar = {"a","b","c"}
for .. in .. 应用而生
语法:
for 变量 in 可迭代对象:
code ...
可迭代对象( 通常用到的是: 容器类型数据 , range对象 , 迭代器 )
2.遍历集合
container = {"taibai","wusir","wuchao","bijiao"}
for i in container:
print(i)
3.遍历列表
'''
Python学习交流,免费公开课,免费资料,
免费答疑,系统学习加QQ群:579817333
'''
container = ["taibai","wusir","wuchao","bijiao"]
for i in container:
print(i)
4.遍历元组
container = ("taibai","wusir","wuchao","bijiao")
for i in container:
print(i)
5.遍历字符串
container = "有时候你的一个微笑,会改变你的一生"
for i in container:
print(i)
6.遍历字典
container = {1:"a",2:"b",3:"c"}
for i in container:
print(i)
7.变量的解包[个数要匹配]
a,b = 1,2
a,b = (1,2)
a,b = [1,2]
#a,b = "567" #字符串有局限性,个数是2个,只能用2个变量收;
#a,b = {"a","b"} 集合有局限性,因为无序;
a,b ={"a":1,"b":2}
print(a,b)
8.遍历等长的二级容器
'''
Python学习交流,免费公开课,免费资料,
免费答疑,系统学习加QQ群:579817333
'''
lst = [("a","b","c"),["d","e","f"],("q","w","e")]
"""
#方法一
for i in lst:
for en in i:
print(en)
"""
for en,line,i in lst:
print(en,line,i)
#en,line,i ("a","b","c")
9.遍历不等长的二级容器
lst = lst = [("a","b","c"),["d","e"],("q",)]
for i in lst:
for en in i:
print(en)
#range 对象
"""
range(start,end,step)
start:开始值
end:结束值
step: 步长
最大值end 取不到的,渠道end这个数之前的那个值
"""
range()作用
res = range(10)
print(res)
1)range当中只有1个值
for i in range(10):
print(i)
2)range当中二个值的情况
for i in range(5,10):
print(i)
3)range当中三个值得情况下
for i in range(1,15,2):
print(i)
4)range倒着打印
'''
Python学习交流,免费公开课,免费资料,
免费答疑,系统学习加QQ群:579817333
'''
for i in range(9,0,-1):
print(i)
5)99乘法表for改写
#while
i = 1
while i<=9:
j = 1
while j <= i:
print("%s*%s=%2s"% (i,j,i*j),end=" ")
j += 1
print()
i += 1
# #for
for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%2d " % (i,j,i*j) ,end = "")
print()
总结:
- while 一般用于复杂的逻辑操作
- for 一般用于数据的遍历
本文来自博客园,作者:I'm_江河湖海,转载请注明原文链接:https://www.cnblogs.com/jhhh/p/16760825.html