高效的循环方式

时间:2020-03-14 13:11:30

标签: python function

我有以下代码,并且可以正常工作,但是由于我想掌握python的技能,所以我想请教您如何改进代码并使其高效的见解。 x

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]

有没有办法自动循环给定值a[0:]?我当时在想字典,但这里有条件陈述。任何帮助,将不胜感激。

2 个答案:

答案 0 :(得分:3)

是的,词典是合适的结构。

{% set ns = namespace() %} 
{% for dict_item in dict %}  
    {% set ns.value = "{{dict_item['name']}}" %}
{% endfor %}

console.log("{{ns.value}}")

答案 1 :(得分:3)

这可以是替代的,例如其他语言中的switch-case(因为python没有switch-case语句)。您可以尝试以下代码:

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))