1

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.

2
  • 1
    How do you plan to treat * in a list as valid syntax? Commented Oct 18, 2015 at 0:24
  • 3
    Aside: Pythonistas prefer to use the identifier lst to refer to a list, rather than list, because list shadows the python builtin. Commented Oct 18, 2015 at 0:29

3 Answers 3

3

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

.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

I'm trying this method out at the moment. What does the '*' mean in (*some_list) ?
You can use * 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/…
2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.