zoukankan      html  css  js  c++  java
  • 默认字典

    通过python,编写一个篮球运动员初选功能的代码:

    1、提示输入姓名;

    2、提示输入身高;

        如果身高大于等于 180 入选,

        如果身高小于等于 180 落选,

    3、把入选的与落选的人,通过字典+列表保存起来

    4、最后打印初选结果!

    脚本——

    import sys

    V1 = []
    V2 = []

    dict1 ={
    'Selected':V1,
    'Uselected':V2
    }
    while True:
    print("Welcome to the screening process")
    choose = input ("Enter yes or no: ")
    if choose.upper() == 'NO':
    break
    if choose.upper() == 'YES':
    name = input("Enter sb's name: ")
    if name.upper() == 'QUIT':
    exit()
    else:
    pass

    height = input("Enter sb's height: ")
    if height.upper() == 'QUIT':
    exit()
    elif int(height) < 180:
    print("Not suitable for basketball! ")
    dict1['Selected'].append(name)
    else:
    print("Welcome to our training with the team")
    dict1['Uselected'].append(name)
    else:
    continue
    print(dict1)

    思路:
    1、定义两个空列表,‘V1’‘V2’
    2、在执行判断的时候,根据判断结果往列表中进行数据添加
    执行效果:

    Welcome to the screening process
    Enter yes or no: yes
    Enter sb's name: james
    Enter sb's height: 210
    Welcome to the screening process
    Enter yes or no: yes
    Enter sb's name: tom
    Enter sb's height: 140
    Not suitable for basketball!
    Welcome to the screening process
    Enter yes or no: yes
    Enter sb's name: harden
    Enter sb's height: 190
    Welcome to the screening process
    Enter yes or no: no
    {'Selected': ['tom'], 'Uselected': ['james', 'harden']}

    通过默认字典的方法,来优化代码:

    仅仅摘列修改部分——

    from collections import defaultdict

    dict1 = defaultdict(list)
    不再需要事先创建空列表与字典了

  • 相关阅读:
    ASP.NET MVC3实现无刷新验证码
    关闭数据库的xp_cmdshell命令以防止黑客攻击
    C#实现100万条数据导入SQL SERVER数据库仅用4秒 (附源码)
    asp.net防止刷新时重复提交介绍
    SQL Server数据库开发中的十大问题
    C#实现WebQQ密码MD5加密算法
    JavaSE基础篇
    Jekins安装与配置(基于majaro)
    Jochen的golang小抄基础篇章二
    JavaSE之面向对象
  • 原文地址:https://www.cnblogs.com/alben-cisco/p/6889571.html
Copyright © 2011-2022 走看看