【发布时间】:2020-01-31 22:36:04
【问题描述】:
如何使用单个开关变量在多个变量之间进行切换?
更新: 澄清意图是在这两组变量之间无限次切换。
当我尝试这个时,我得到以下错误。
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
【问题讨论】:
-
这里不需要
i或switch:for response, greeting in (a1, b1), (a2, b2):。 -
或者更习惯用法:
responses = ['yes', 'no']; greetings = ['hello', 'goodby']; for response, greeting in zip(responses, greetings): -
感谢您的帮助。我更新以更清楚地说明问题的意图。两组变量之间的切换时间不定。
-
我将 that 写为
for ap, aa in islice(cycle([(a1,b1), (a2,b2)]), N):(其中islice和cycle是从itertools导入的)。或者,如果您需要/想要i、for i, (ap, aa) in zip(range(N), cycle(...))。 -
错误来自优先级问题:
(a1, b1) if switch else (a2, b2).
标签: python if-statement boolean