Reputation: 241
Lets say I have a simple list as lis = [5, *, 2]
Is it possible to do something along the line of:
print(reduce(lambda x,y,z: float(x) y float(z), lis))
10
I'd like to use the string given in the list to determine the operand.
Upvotes: 1
Views: 140
Reputation: 6606
Operators can't be passed around in Python -- reduce(+, [1,2,3])
would give you a SyntaxError
. Similarly, your operator in the middle of the list would as well.
If you're looking to use strings to look up operators, you can construct a dictionary using the operator
module.
SYMBOL_TO_OPERATOR = {"*": operator.mul,
"+": operator.add, ...}
Those are just normal methods though -- you can't use them with 'infix' notation as you can the symbols.
Additionally, this doesn't make much sense as a reduce
operation (nor would that be very idiomatic python). You could easily do something like:
statements = [[1, "*", 5], [2, "+", 9]]
results = [SYMBOL_TO_OPERATOR[symbol](a, b) for a, symbol, b in statements]
Upvotes: 2
Reputation: 11994
Let me know if I am misunderstanding, but I believe something like below would accomplish what you are asking:
import operator
operators = {
'*': operator.mul,
'/': operator.div
}
dynamic_operator = lambda x,y,z: operators[y](x, z)
some_list = [5, '*', 5]
print dynamic_operator(*some_list)
You would need to expand on the operators
dictionary to encompass all the operations you want to handle dynamically. For more operator functions, see: https://docs.python.org/2/library/operator.html
Upvotes: 2
Reputation: 6563
First off, you can't place the *
operator in a list, as it is not a value in Python. Instead you can use the mul
function from the operator
package:
from operator import mul
Then, assuming that you have the following list:
lst = [5, mul, 2]
you can do the following:
a, op, b = lst
print(op(a,b))
which should print:
10
.
Upvotes: 3