[英]Python 3: strings to variable with list comprehension
在 Python 2.7 中,我曾經能夠使用以下代碼(我使用的是emcee包):
def main():
from emcee import moves
emcee_moves = ['KDEMove(),0.5', 'DEMove(),0.5']
mv = [(eval("moves." + _)) for _ in emcee_moves]
if __name__ == '__main__':
main()
我使用它是因為我通過輸入參數文件(這是更大代碼的一小部分)提供“移動”,這意味着它們被作為字符串讀取。 在 Python 3.x 中,現在拋出:
*** NameError: name 'moves' is not defined
這顯然與這個舊問題中提到的這個不會修復錯誤有關: Eval scope in Python 2 vs. 3 。
我還讀到,通常不鼓勵使用eval()
。 那么我的問題是:如何復制上述用於 Python 2.7 的代碼?
編輯
這是失敗的實際代碼。 它需要在一個函數內,否則它不會失敗。
正如皮特所說,您的示例適用於 python 3.6.8。 但是,另一種做你想做的事情的方法是:
from emcee import moves
emcee_moves = [('KDEMove', 0.5), ('DEMove', 0.5)]
mv = [(getattr(moves, method)(), val) for method, val in emcee_moves]
getattr 通常比 eval 更安全。
您始終可以用常規循環替換列表理解。 不那么花哨,但提供相同的功能。
雖然I have Python 3.8.0 and the code works as expected - without any errors.
,正如我的評論所說,仍然可以在沒有任何eval()
情況下執行這些操作。
您想從模塊中動態獲取一個類。 您可以為此使用getattr()
。
from emcee import moves
emcee_moves = ['KDEMove', 'DEMove']
mv = [getattr(moves, _)() for _ in emcee_moves]
輸出:
In [22]: mv = [getattr(moves, _)() for _ in emcee_moves]
In [23]: mv
Out[23]:
[<emcee.moves.kde.KDEMove at 0x7f2bf8b98a90>,
<emcee.moves.de.DEMove at 0x7f2bf90b08e0>]
我不完全確定為什么那些,0.5
后綴在那里( __init__
參數,也許?) ,但“要點”寫在上面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.