简体   繁体   English

Python:为此做的更有效的方法

[英]Python : more efficient way to do for this

I'm a beginner in python and i'm wondering if there is a classy way to do this :我是 python 的初学者,我想知道是否有一种优雅的方法来做到这一点:

if societe_var == 'apple':
    bu_list = bu_list_apple
elif societe_var == 'banana':
    bu_list = bu_list_banana
elif societe_var == 'pear' :
    bu_list = bu_list_pear
else :
    bu_list = bu_list_cherry

Best regards,此致,

Kair0凯尔0

Use a dictionary:使用字典:

bu_list_map = {
    'apple': bu_list_apple,
    'banana': bu_list_banana,
    'pear': bu_list_pear
}

bu_list = bu_list_map.get(societe_var, default=bu_list_cherry)

Use the default argument to the .get() method to handle the fallback case使用.get()方法的default参数来处理回退情况

Put your possible values in a dict and use .get() to get one of them (or a default if not found):将您可能的值放入 dict 并使用.get()获取其中之一(如果未找到则为默认值):

bu_lists = {
    'apple': bu_list_apple,
    'banana': bu_list_banana,
    'pear': bu_list_pear,
}
bu_list = bu_lists.get(societe_var, bu_list_cherry)

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

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