变多变量的高效ifelif

2024-06-14 06:06:15 发布

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

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

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

我想使用描述的dict方法here,但是如何修改它来更改多个变量呢?我希望它像这样工作:

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

或者,如果不创建一个函数并分别对所有条件进行硬编码,就不能实现这一点吗?你知道吗


Tags: 方法函数testnoneifherefoobar
3条回答

这将更改模块的全局命名空间中的变量

>>> options = {'foo': ('a',1), 'bar': ('b',2)}
>>> 
>>> def reassign_variables(options, test, default):
...     var, val = options.get(test, default)
...     globals()[var] = val
... 
>>> 
>>> a, b, c = None, None, None
>>> reassign_variables(options, "foo", ('c',3))
>>> a,b,c
(1, None, None)
>>> reassign_variables(options, "baz", ('c',3))
>>> a,b,c
(1, None, 3)
>>> 

使用^{}方法,如果我没弄错的话:

test = 'foo'
options.update({test:('a',12)})

您可以将值重新指定给变量

a,b,c = None, None, None
options = {'foo': (1,b,c), 'bar': (a,1,c)}
default = (a,b,1)
test = 'foo'
a,b,c = options.get(test,default)

相关问题 更多 >