首页 > 解决方案 > 如何在 Python 中使用 if-else 语句在多个变量之间切换

问题描述

如何使用单个开关变量在多个变量之间进行切换?

更新: 澄清意图是在这两组变量之间无限次切换。

当我尝试这个时,我收到以下错误。

a1= 'process1'
a2 = 'process2'

b1 = 'action1'
b2 = 'action2'

switch = True # the switch to indicate which set of variables to use
N = 10        # the number of times to switch between the two sets of variables

# alternate between two sets of variables N times
for i in range (N):
    active_process, active_action = a1, b1 if switch else a2, b2

    print("active_process: %s, active_action is: %s" %(active_process, active_action))
    switch = not switch

追溯:

Traceback (most recent call last):
  File "/home/username/.PyCharm2019.3/config/scratches/scratch_10.py", line 10, in <module>
    active_process, active_action = a1, b1 if switch else a2, b2
ValueError: too many values to unpack (expected 2)

Process finished with exit code 1

标签: pythonif-statementboolean

解决方案


你把它弄得太脆弱了。您有一个问候/响应值表和一个布尔值,告诉您使用哪个。只需使用直接访问列表执行此操作:

table = [ ("process1", "action1"),
          ("process2" , "action2")
        ]

N = 10
for i in range(10):
    print("%s, the answer is: %s" % table[i %2])

或者,使用字典:

table = { True:  ("process1", "action1"),
          False: ("process2" , "action2")
        }
N = 10
for i in range(N):
    print("%s, the answer is: %s" % table[i %2])

推荐阅读