• 技术文章 >Python技术 >Python基础教程

    python for语句的应用场景

    小妮浅浅小妮浅浅2021-09-23 10:06:42原创1948

    应用场景

    1、当迭代遍历嵌套的数据类型时,例如,一个列表包含多个字典。

    2、需求判断字典中是否有指定值。

    3、如有,提示并退出循环。

    4、如果不存在,希望在整个循环结束后得到统一的提示。

    实例

    students = [
        {"name": "阿土",
         "age": 20,
         "gender": True,
         "height": 1.7,
         "weight": 75.0},
        {"name": "小美",
         "age": 19,
         "gender": False,
         "height": 1.6,
         "weight": 45.0},
    ]
     
    find_name = "阿土"
     
    for stu_dict in students:
     
        print(stu_dict)
     
        # 判断当前遍历的字典中姓名是否为find_name
        if stu_dict["name"] == find_name:
            print("找到了")
     
            # 如果已经找到,直接退出循环,就不需要再对后续的数据进行比较
            break
     
    else:
        print("没有找到")
     
    print("循环结束")

    以上就是python for语句的应用场景,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python for语句
    品易云
    上一篇:python循环遍历如何理解 下一篇:python如何模拟用户自动打卡

    相关文章推荐

    • python可选参数是什么• python logging常见的解决方案• python如何判断字符串被驻留• python字符串如何访问字符• python异常处理的流程• python中__new__的使用注意• python索引的顺序和倒序• python循环遍历如何理解

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网