簡體   English   中英

如何在 Python 中使用 if-else 語句在多個變量之間切換

[英]How to switch between multiple variables using an if-else statement in Python

如何使用單個開關變量在多個變量之間進行切換?

更新:澄清意圖是無限次地在這兩組變量之間切換。

當我嘗試這個時,我收到以下錯誤。

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])

使用列表打包和解包項目給出了預期的結果:

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 

# 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

輸出:

active_process: process1, active_action is: action1
active_process: process2, active_action is: action2
active_process: process1, active_action is: action1
active_process: process2, active_action is: action2
active_process: process1, active_action is: action1
active_process: process2, active_action is: action2
active_process: process1, active_action is: action1
active_process: process2, active_action is: action2
active_process: process1, active_action is: action1
active_process: process2, active_action is: action2

Process finished with exit code 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM