从字符串inpu收集数字数据

2024-06-09 15:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到他们的信用评级,如AAA,A,BBB等用户输入,然后分配一个利率给这个。例如,如果用户有一个良好的信用评级,如AAA,我会收取1%的利率

我已经插入了我在VBA中为这个特定函数使用的代码,这样你就知道我想要什么/它是如何工作的,尽管我删除了许多行,因为我添加代码只是为了更好地显示我正在尝试做的事情

creditRate = InputBox("Please enter credit rating:")

If creditRate = "AAA" Then GoTo intcalc Else
If creditRate = "A" Then GoTo intcalc Else
If creditRate = "BBB" Then GoTo intcalc Else
If creditRate = "BB" Then GoTo intcalc Else
If creditRate = "CCC" Then GoTo intcalc Else
If creditRate = "DDD" Then GoTo intcalc Else

If creditRate = "AAA" Then intRate = 0.01 Else
If creditRate = "A" Then intRate = 0.03 Else
If creditRate = "BBB" Then intRate = 0.05 Else
If creditRate = "BB" Then intRate = 0.06 Else
If creditRate = "CCC" Then intRate = 0.08 Else
If creditRate = "DDD" Then intRate = 0.1 Else

Tags: 代码用户ifelsebbbcccbbthen
2条回答

在Python中,这很可能是使用dict计算的,dict是一种基于散列的数据结构,允许查找(相当)任意键。这样的dict可以如下创建

rate_dict = {"AAA": 0.01, "A": 0.03, "BBB", 0.05, "BB", 0.06, "CCC": 0.08, "DDD": 0.1}

然后使用

int_rate = rate_dict[credit_rate]

如果从用户输入设置了credit_rate,您可能需要检查它是否有效。你可以用它来做

if credit_rate in rate_dict:
    ...

如果要向用户请求有效的输入,请从无效值开始,然后迭代,直到用户提供了有效的输入。一个简单的方法就是

credit_rate = '*'
while credit_rate not in rate_dict:
    credit_rate = input("Credit rating: ")

如果您想提供错误消息,那么在可接受值上带有break的无限循环可能更具可读性

while True:
    credit_rate = input("Credit rating: ")
    if credit_rate in rate_table:
        int_rate = rate_dict[credit_rate]
        break
    print(credit_rate, "is not a known credit rating"

使用python2的读者应该注意使用raw_input内置函数,因为在旧版本中input尝试将输入作为Python表达式进行求值

Python还提供了一个默认字典,如果字典中不存在键,它将返回一个默认值

from collections import defaultdict
rates = defaultdict(lambda: None, { 
                     "AAA" : 0.01, "A" : 0.03,
                     "BBB" : 0.05, "BB" : 0.06, 
                     "CCC" : 0.08, "DDD" : 0.1  
                      })

所以呢

rate = rates['AAA'] #rate = 0.01

以及

rate = rates['D']) #rate = None

相关问题 更多 >