for循环 字符串

  1. strs = "abcdefg"
  2. # 循环字符串,会将字符串中每个字符循环一遍
  3. for s in strs:
  4. print(s)

for 循环list,tuple,set

  1. lists = ["books","names","helloworld"]
  2. for l in lists:
  3. print(l)
  1. lists = ("books","names","helloworld")
  2. for l in lists:
  3. print(l)
  1. lists = {"books","names","helloworld","books"}
  2. for l in lists:
  3. print(l)

for 循环dict

  1. user_info = {
  2. "name":"xiaowang",
  3. "age":30,
  4. "salary": 25000,
  5. "spending": 10000,
  6. "friends": ["xiaozhang","xiaowang","laowang"],
  7. "hobby": [
  8. {"name":"reading","year":8},
  9. {"name":"game","year":20},
  10. {"name":"sport","year":10}
  11. ]
  12. }
  13. for key,val in user_info.items():
  14. print(f'{key}--{val}')

字典数据类型是键值对的方式,循环的时候需要获取到字典key 和value。

  1. user_info = {
  2. "name":"xiaowang",
  3. "age":30,
  4. "salary": 25000,
  5. "spending": 10000,
  6. "friends": ["xiaozhang","xiaowang","laowang"],
  7. "hobby": [
  8. {"name":"reading","year":8},
  9. {"name":"game","year":20},
  10. {"name":"sport","year":10}
  11. ]
  12. }
  13. for key,val in user_info.items():
  14. print(f'{key}--{val}')
  15. # == 表示判断 判断两个值是否相等 如果key的值为 friends
  16. if key == "friends":
  17. # 对val 进行循环 当if 条件成立的时候才会执行下面的for循环语句
  18. for name in val:
  19. print(f"name的值为:{name}")

练习

针对如下json格式数据进行循环。

  1. user_info = {
  2. "name":"xiaowang",
  3. "age":30,
  4. "salary": 25000,
  5. "spending": 10000,
  6. "friends": ["xiaozhang","xiaowang","laowang"],
  7. "hobby": [
  8. {"name":"reading","year":8},
  9. {"name":"game","year":20},
  10. {"name":"sport","year":10}
  11. ]
  12. }

如果 key的值为 ‘hobby’, 对hobby的值进行再次循环。

  1. for key,val in user_info.items():
  2. print(f'{key}--{val}')
  3. # == 表示判断 判断两个值是否相等 如果key的值为 friends
  4. if key == "hobby":
  5. # 针对hobby值中的list列表进行循环
  6. for hobby in val:
  7. # list中的每个字典 {'name': 'reading', 'year': 8}
  8. print(f"hobby is {hobby}")
  9. for k,v in hobby.items():
  10. print(f'{k}---{v}')