Transforming Strings into Operators
The question presents a challenge: given a string representing an operator, such as "+", how can we convert it into the corresponding Python operator function, like operator.add?
Lookup Table Approach
As the answer suggests, an effective solution involves using a lookup table. This table associates operator strings with their corresponding functions:
import operator ops = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "**": operator.pow }
We can then use this table to retrieve the operator function based on the input string:
op_string = "+" # represents the plus operator # Look up the corresponding operator function op_function = ops[op_string] # Use the function to perform an operation result = op_function(1, 2) # returns 3 print(result)
This approach provides a flexible way to handle different operators and their associated functions. It allows us to easily extend the lookup table to include additional operators as needed.
以上是如何將字串轉換為Python運算子函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!