简体   繁体   English

高效的循环方式

[英]Efficient way to loop

I have the following code and it works but as I want to master my skills in python I would like to get your opinion how to improve the code and make it efficient.我有以下代码并且它可以工作,但是因为我想掌握我的 Python 技能,所以我想征求您的意见,如何改进代码并使其高效。 x X

value - certain value user selects value - 用户选择的特定值

a=[10,30,50,20]


def math():
    if value =='Math':return a[0]
    if value =='Biology':return a[1]
    if value =='Chemistry':return a[2]
    if value =='Literature':return a[3]

Is there any way to loop automatically a[0:] with values given?有没有办法用给定的值自动循环a[0:] I was thinking of dictionary but here I am given conditional statements.我正在考虑字典,但在这里我得到了条件语句。 Any help would be appreciated.任何帮助,将不胜感激。

Yes, a dictionnary would be an appropriate structure.是的,字典将是一个合适的结构。

grades = {"Math": 10,
          "Biology": 30,
          "Chemistry": 50,
          "Literature": 20}

topic = input()
try:
    print(grades[topic])
except KeyError:
    print(f'There is no available grade for the topic "{topic}".')

This can be alternate, like switch-case (since python dose not have switch-case statements) in other languages.这可以是替代的,就像其他语言中的 switch-case(因为 python 没有 switch-case 语句)。 You can try the below code:你可以试试下面的代码:

def switch_case(arg):
    switcher = {
        'Math' : 10,
        'Biology' : 30,
        'Chemistry' : 50,
        'Literature' : 20
    }
    return switcher.get(arg, 'Invalid subject!')

subject = input('Enter the subject : ')
print(switch_case(subject))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM