我正在試驗如何在我的代碼中壓縮 if 陳述句。我有一個我正在處理的專案,它有幾個“if”陳述句(太多無法跟蹤),并且想找出一種壓縮它們的方法。顯然,這涉及一個 for 回圈,但我無法在此回圈中添加其他操作。
我想出了以下作業示例來演示我的問題:
num=6
if_options = [num==5, num==6]
for i in range(len(if_options)):
if if_options[i]:
print(num)
我想在代碼中添加一個額外的部分。這個額外的部分將在 if 陳述句中執行一個操作。請參閱以下非作業示例作為我嘗試完成的框架:
num=6
if_options = [num==5, num==6]
operations = [num=num 1, num=num-1]
for i in range(len(if_options)):
if if_options[i]:
operations[i]
print(num)
無論出于何種原因,它都不會執行代碼的操作部分并因語法錯誤而失敗。它不允許我在串列中宣告命令“num=num 1”(不帶引號),但是這個宣告對于執行命令是必要的。我覺得我錯過了一件小事,應該很容易解決。先感謝您!!
uj5u.com熱心網友回復:
這里的問題是在創建操作串列時會評估這些操作。你想把它們寫成字串,然后eval/exec他們在回圈中。我假設您還希望在回圈中評估條件。
num = 6
if_options = ['num==5', 'num==6']
operations = ['num=num 1', 'num=num-1']
for i in range(len(if_options)):
if eval(if_options[i]):
exec(operations[i])
print(num)
uj5u.com熱心網友回復:
為什么不是函式?
def check(inp):
#you can do some logic and type checking here
return type(inp)==int # for example, or return arguments to pass to the operatiins
def operation(inp2):
if inp2: # check if true or not empty, as an example
#do some operations
# and then you do something like
for x in input_of_things:
operation( check( x ) )
uj5u.com熱心網友回復:
您也可以使用 lambda 運算式。
num = 6
if_option_checks = [lambda x: x == 5, lambda x: x == 6]
operations = [lambda x: x 1, lambda x: x - 1]
for check, operation in zip(if_option_checks, operations):
if check(num):
num = operation(num)
或者你可以使用字典和 lambda 運算式
num = 6
if_option_checks = {"add": lambda x: x == 5, "sub": lambda x: x == 6}
operations = {"add": lambda x: x 1, "sub": lambda x: x - 1}
for key, check in if_option_checks.items():
if check(num):
num = operations[key](num)
uj5u.com熱心網友回復:
也許 switch 陳述句結構會有所幫助。
首先定義一個開關函式:
def switch(v): yield lambda *c: v in c
然后在一次迭代 for 回圈中使用,為 switch 值生成一個 case 函式:
for case in switch(num):
if case(5):
num = num 1
break
if case(6):
num = num - 1
break
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364516.html
上一篇:C 在這種情況下,“對非常量參考的初始值必須是左值”的錯誤是什么意思?
下一篇:PythonException:'TypeError:divmod()不支持的運算元型別:'NoneType'和'int''
