stringExp = "2^4"
intVal = int(stringExp) # Expected value: 16
Run Code Online (Sandbox Code Playgroud)
这将返回以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
with base 10: '2^4'
Run Code Online (Sandbox Code Playgroud)
我知道eval可以解决这个问题,但是不是有更好的 - 更重要的 - 更安全的方法来评估存储在字符串中的数学表达式吗?
在我的代码中,我eval用来评估用户给出的字符串表达式.有没有办法编译或以其他方式加快这种说法?
import math
import random
result_count = 100000
expression = "math.sin(v['x']) * v['y']"
variable = dict()
variable['x'] = [random.random() for _ in xrange(result_count)]
variable['y'] = [random.random() for _ in xrange(result_count)]
# optimize anything below this line
result = [0] * result_count
print 'Evaluating %d instances of the given expression:' % result_count
print expression
v = dict()
for index in xrange(result_count):
for name in variable.keys():
v[name] = variable[name][index]
result[index] = eval(expression) # <-- option ONE
#result[index] = math.sin(v['x']) * …Run Code Online (Sandbox Code Playgroud) 我正在尝试找到一种传递字符串(来自Python世界之外!)的方法,该字符串可以被解释为**kwargs一旦到达Python端。
我一直在尝试使用这个 pyparsing 示例,但是此示例中传递的字符串太具体,而且直到现在我才听说过 pyparsing 。我正在努力使其更加人性化,并且对间距等的微小差异具有鲁棒性。例如,我想传递以下内容。
input_str = "a = [1,2], b= False, c =('abc', 'efg'),d=1"
desired_kwargs = {a : [1,2], b:False, c:('abc','efg'), d:1}
Run Code Online (Sandbox Code Playgroud)
但当我尝试这段代码时,没有爱。
from pyparsing import *
# Names for symbols
_quote = Suppress('"')
_eq = Suppress('=')
# Parsing grammar definition
data = (
delimitedList( # Zero or more comma-separated items
Group( # Group the contained unsuppressed tokens in a list
Regex(u'[^=,)\s]+') + # Grab everything up to an equal, comma, endparen or whitespace …Run Code Online (Sandbox Code Playgroud)