我有蟒蛇替代一個自變量x爲VAR串蟒蛇
def func(x):
# x is int
for cell in list1:
# gets each cell
print cell
功能如何使用eval來計算新的字符串?
有什麼想法嗎?
謝謝
我有蟒蛇替代一個自變量x爲VAR串蟒蛇
def func(x):
# x is int
for cell in list1:
# gets each cell
print cell
功能如何使用eval來計算新的字符串?
有什麼想法嗎?
謝謝
你不想替代。你想評估表達。我建議你嘗試這樣的事:
variables = { x: 900 }
cell = 'x+3'
result = eval(cell, locals=variables)
這將使用Python語法評估cell
表達。只要你的單元格公式足夠簡單,那可能就沒問題。如果您開始嘗試執行Excel電子表格公式,則需要做更多工作。
您首先意識到字符串列表是對函數列表進行編碼的可怕方法。 'list1'應該是'[lambda x:x + 3,lambda x:x/3,lambda x:x * 3]'。 – chepner
[評估字符串中的數學表達式]可能的重複(http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – timgeb