python - 如何在 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
解决方案
你把它弄得太脆弱了。您有一个问候/响应值表和一个布尔值,告诉您使用哪个。只需使用直接访问列表执行此操作:
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])
推荐阅读
- c# - 将数据传递给其他域上的图片导出功能?
- angular - Angular 5 chart.js onclick 返回空数组
- django - 为什么 Django 单元测试没有看到引发的异常?
- javascript - Vue 组件在哪里导入?
- visualization - 在 Power BI 图中绘制多条线
- r - 从R中的多个pdf文件中提取数据
- spreadsheet - 如何在谷歌表中将今天()函数的输出作为字符串
- javascript - 保留被拖动的元素
- postgresql - PostgreSQL 表移动平均值
- django - 传入 4 个参数,但被 Django 服务器读取为 5