Python中for循环是一个通用的序列迭代器:它可以遍历任何有序序列和其他可迭代对象内的元素。for循环可用于字符串,列表,元组或其他内置可迭代对象。
其语法形式如下:
"""当运行for循环时,会逐个将可迭代对象object中的元素赋值给target,然后为每个元素执行循环主体。""" for target in object: # statements1 if test: break # 跳出循环 if test: continue # 结束本次循环else: statements2 # 上面没有执行break语句,就会执行到这里
1:简单应用
# 字符串s = 'ixusy88' for x in s: print(x) # 列表lst = ['123','abc','456']for x in lst: print(x) # 元组st = ('123','abc','456')for x in st: print(x)
2:for循环中的元组赋值
# 1:lst = [(1,2),(3,4),(5,6)]for t in lst: a,b = t print(a,b)"""输出1 23 45 6""" for (a,b) in lst: print(a,b) """输出1 23 45 6"""#2:lst = [((1,2),3),((4,5),6)]for t in lst: print(t) (a,b),c = t print(a,b,c) """输出:((1, 2), 3)1 2 3((4, 5), 6)4 5 6""" lst = [((1,2),3),((4,5),6)]for ((a,b),c) in lst: print(a,b,c)"""输出:1 2 34 5 6""" # 3:字典:dic = {'name':'ixusy88','age':18}for key in dic: print(key,'-->',dic[key]) """输出:name --> ixusy88age --> 18""" dic = {'name':'ixusy88','age':18}for k,v in dic.items(): print(k,'-->',v) """name --> ixusy88age --> 18"""
3:计数器循环:range
"""print(help(range))class range(object) | range(stop) -> range object | range(start, stop[, step]) -> range object ........"""# 0到9for x in range(10): print(x,end=',')print('') # 输出 0,1,2,3,4,5,6,7,8,9, # 1到9for x in range(1,10): print(x,end=',')print('')# 输出 1,2,3,4,5,6,7,8,9, # 1到9,间隔为2for x in range(1,10,2): print(x,end=',')print('')# 输出 1,3,5,7,9, # 1到9,间隔为3for x in range(1,10,3): print(x,end=',')print('')# 输出 1,4,7,
4:偏移量和元素:enumerate
print('--字符串-1-:',)# 字符串s = 'ixusy88' for x in s: print(x) print('--字符串-2-:',)# 带偏移量for i,x in enumerate(s): print(i,x) print('--列表-1-:',)# 列表lst = ['123','abc','456']for x in lst: print(x) print('--列表-2-:',)for i,x in enumerate(lst): print(i,x) print('--元组-1-:',)# 元组st = ('123','abc','456')for x in st: print(x) print('--元组-2-:',)for i,x in enumerate(st): print(i,x)
5:推导
# 推导# 列表推导t = [x**x for x in range(5)]print(t) # 集合t = {x**x for x in range(5)}print(t) # 字典t = {x:x**x for x in range(5)}print(t)
"""[1, 1, 4, 27, 256]{256, 1, 27, 4}{0: 1, 1: 1, 2: 4, 3: 27, 4: 256}"""
领取专属 10元无门槛券
私享最新 技术干货