[英]Using exec() to run lambda function from string
我希望能夠從txt文件引入lambda函數,並使其能夠像正常的代碼段一樣運行。
chain = "What has to be broken up"
reduction = 'lambda chain: chain[0:8]'
x = exec(reduction)
print(x) #only prints out 'None'
print(exec(x = reduction)) #causes error
print(exec(reduction)) #prints out 'None'
我希望輸出是字符串鏈的前8個字符“ What have”。 如何使這項工作運行該功能?
要運行函數,必須在其后使用()
。
要獲取字符串中表達式的值,您需要使用eval()
而不是exec()
。 請參閱eval,exec和compile有什么區別? 。
由於您的lambda函數具有參數,因此在調用它時需要為其提供參數。
chain = "What has to be broken up"
reduction = 'lambda c: c[0:8]'
x = eval(reduction)(chain)
print(x)
如果不想給它一個參數,則應刪除該參數。 但是您仍然需要提供一個空的參數列表。
chain = "What has to be broken up"
reduction = 'lambda: chain[0:8]'
x = eval(reduction)()
print(x)
我不確定我是否了解您要執行的操作,但這是一個猜測。 它使用eval
而不是exec()
因為reduction
是一個表達式:
chain = "What has to be broken up"
reduction = 'lambda string: string[0:8]'
x = eval(reduction)(chain)
print(x) # -> What has
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.