Skip to main content
 首页 » 编程设计

python之用于更改多个变量的高效 if-elif

2025年02月15日8grandyang

<分区>

我有几个变量,其中一些我需要在特定条件下更改。

test = 'foo' 
a, b, c = None, None, None 
if test == 'foo': 
    a = 1 
elif test == 'bar': 
    b = 2 
else: 
    c = 3 

我想使用 here 中描述的字典方法,但如何修改它以更改多个变量?我希望它像这样工作:

options = {'foo': ('a',1), 'bar': ('b',2)} 
reassign_variables(options,test, ('c',3)) 

或者如果不创建一个函数并单独对所有条件进行硬编码,就不能做到这一点吗?