for循环在Python中是一个通用的序列迭代器:可以遍历任何有序的序列对象内的元素。
可用于字符串,列表,元组,其他内置可迭代对象,以及通过类所创建的新对象。
语法格式: for in : else: Python运行for循环时,会逐个将序列对象中的元素赋值给目标,然后为每个元素执行循环主体。 循环主体一般使用赋值的目标来引用序列中当前的元素。 for语句也支持一个选用的else块,它的工作就像是在while循环中一样:若循环离开时没有碰到break语句,就会执行。break 和 continue 语句也可用于for循环中。 for循环完整的格式: for in : if : break if : continue else: 【迭代遍历字典】 card_list = [{"name": "ang", "qq": "4355"}, {"name": "bng", "qq": "5555"}] for card in card_list: print(card) 复制代码 stu_name = [{"name": "小梅"}, {"name": "小明"}] for stu in stu_name: print(stu) if stu["name"] == "小梅": print("找到了") break else: print("没找到")
else:
Python运行for循环时,会逐个将序列对象中的元素赋值给目标,然后为每个元素执行循环主体。
循环主体一般使用赋值的目标来引用序列中当前的元素。
for语句也支持一个选用的else块,它的工作就像是在while循环中一样:若循环离开时没有碰到break语句,就会执行。break 和 continue 语句也可用于for循环中。
for循环完整的格式:
for in : if : break if : continue else: 【迭代遍历字典】 card_list = [{"name": "ang", "qq": "4355"}, {"name": "bng", "qq": "5555"}] for card in card_list: print(card) 复制代码 stu_name = [{"name": "小梅"}, {"name": "小明"}] for stu in stu_name: print(stu) if stu["name"] == "小梅": print("找到了") break else: print("没找到")
if : break
if : continue
【迭代遍历字典】
card_list = [{"name": "ang", "qq": "4355"}, {"name": "bng", "qq": "5555"}] for card in card_list: print(card)
复制代码 stu_name = [{"name": "小梅"}, {"name": "小明"}] for stu in stu_name: print(stu) if stu["name"] == "小梅": print("找到了") break else: print("没找到")