I am trying to use a list that has operations attached to them, but i can't get the numbers out of the list. Here is the list.
mylist=["+1", "-2", "*2"]
I was wondering if there was a way to put them together as a float, and then do the operation so it would do 1-2*2 and output the answer. Smaller the better. thanks :) the expected output is -2.
You can use a dict
to map symbols to operations (that are all defined in operator
) and regular expressions to parse the strings in order to avoid evil eval
. This applies the operations in the list from left to right, regardless of mathematical operator precedence:
import re
from operator import add, sub, mul, truediv # use 'floordiv' for integer division
def calc(lst):
ops = {'+': add, '-': sub, '*': mul, '/': truediv}
result = 0
for x in lst:
op, num = re.match(r'([+\-\*/])(\d+)', x).groups()
result = ops[op](result, int(num))
return result
>>> calc(['+1', '-2', '*2'])
-2
>>> calc(['+1', '-2', '*2', '+7', '*3'])
15