for循环 字符串
strs = "abcdefg"
# 循环字符串,会将字符串中每个字符循环一遍
for s in strs:
print(s)
for 循环list,tuple,set
lists = ["books","names","helloworld"]
for l in lists:
print(l)
lists = ("books","names","helloworld")
for l in lists:
print(l)
lists = {"books","names","helloworld","books"}
for l in lists:
print(l)
for 循环dict
user_info = {
"name":"xiaowang",
"age":30,
"salary": 25000,
"spending": 10000,
"friends": ["xiaozhang","xiaowang","laowang"],
"hobby": [
{"name":"reading","year":8},
{"name":"game","year":20},
{"name":"sport","year":10}
]
}
for key,val in user_info.items():
print(f'{key}--{val}')
字典数据类型是键值对的方式,循环的时候需要获取到字典key 和value。
user_info = {
"name":"xiaowang",
"age":30,
"salary": 25000,
"spending": 10000,
"friends": ["xiaozhang","xiaowang","laowang"],
"hobby": [
{"name":"reading","year":8},
{"name":"game","year":20},
{"name":"sport","year":10}
]
}
for key,val in user_info.items():
print(f'{key}--{val}')
# == 表示判断 判断两个值是否相等 如果key的值为 friends
if key == "friends":
# 对val 进行循环 当if 条件成立的时候才会执行下面的for循环语句
for name in val:
print(f"name的值为:{name}")
练习
针对如下json格式数据进行循环。
user_info = {
"name":"xiaowang",
"age":30,
"salary": 25000,
"spending": 10000,
"friends": ["xiaozhang","xiaowang","laowang"],
"hobby": [
{"name":"reading","year":8},
{"name":"game","year":20},
{"name":"sport","year":10}
]
}
如果 key的值为 ‘hobby’, 对hobby的值进行再次循环。
for key,val in user_info.items():
print(f'{key}--{val}')
# == 表示判断 判断两个值是否相等 如果key的值为 friends
if key == "hobby":
# 针对hobby值中的list列表进行循环
for hobby in val:
# list中的每个字典 {'name': 'reading', 'year': 8}
print(f"hobby is {hobby}")
for k,v in hobby.items():
print(f'{k}---{v}')