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.
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
.
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
* to unpack lists into arguments. E.g. doing somefunction(*[a, b]) is the same as doing somefunction(a, b), and can be used when arguments are completely dynamic. For more information, see: docs.python.org/2/tutorial/…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]
*in a list as valid syntax?lstto refer to a list, rather thanlist, becauselistshadows the python builtin.