使用带有数字 python 的操作的列表进行计算
Calculations using a list with operations with numbers python
我正在尝试使用附有操作的列表,但无法从列表中获取数字。这是列表。
mylist=["+1", "-2", "*2"]
想知道有没有办法把它们拼成一个float,然后运算1-2*2然后输出答案。越小越好。谢谢 :) 预期输出是 -2.
通过将您的示例视为字符串,可以在列出的每个操作之后计算输出,假设输入从左到右优先处理:
from collections import namedtuple
import re
token = namedtuple('token', 'operator, value')
mylist="[+1, -2, *2]"
data = re.findall('[\+\-\*]|\d+', mylist)
final_data = [data[i:i+2] for i in range(0, len(data), 2)] #create tokenized list
tokens = [token(a, int(b)) for a, b in final_data]
operations = {'+':lambda x,y:x+y, '-':lambda x, y:x-y, '*':lambda x, y:x*y}
total_val = 0
for token in tokens:
total_val = operations[token.operator](total_val, token.value)
输出:
-2
您可以使用 dict
将符号映射到操作(均在 operator
) and regular expressions to parse the strings in order to avoid evil eval
中定义)。无论数学运算符优先级如何,这都会从左到右应用列表中的操作:
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
我正在尝试使用附有操作的列表,但无法从列表中获取数字。这是列表。
mylist=["+1", "-2", "*2"]
想知道有没有办法把它们拼成一个float,然后运算1-2*2然后输出答案。越小越好。谢谢 :) 预期输出是 -2.
通过将您的示例视为字符串,可以在列出的每个操作之后计算输出,假设输入从左到右优先处理:
from collections import namedtuple
import re
token = namedtuple('token', 'operator, value')
mylist="[+1, -2, *2]"
data = re.findall('[\+\-\*]|\d+', mylist)
final_data = [data[i:i+2] for i in range(0, len(data), 2)] #create tokenized list
tokens = [token(a, int(b)) for a, b in final_data]
operations = {'+':lambda x,y:x+y, '-':lambda x, y:x-y, '*':lambda x, y:x*y}
total_val = 0
for token in tokens:
total_val = operations[token.operator](total_val, token.value)
输出:
-2
您可以使用 dict
将符号映射到操作(均在 operator
) and regular expressions to parse the strings in order to avoid evil eval
中定义)。无论数学运算符优先级如何,这都会从左到右应用列表中的操作:
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