python - 使用 eval 对列表求和

标签 python list eval

我有一个这样的列表

yy = ['A1', 'B1', 'C1']

A1B1C1 的值在这样的字典中

ff = {
    'A1': 10,
    'B1': 20,
    'C1': 30
}

现在我想用 ff 中的值对列表求和。这是我尝试做的

p = "sum(lst)"

eval(p, {'lst': yy}, ff)

但我得到 TypeError: unsupported operand type(s) for +: 'int' and 'str'。 在调试过程中,我发现如果我这样做,p = "sum([A1, B1, C1])" 和 eval 它会起作用。不确定为什么会这样?

完整代码:

ff = {
    'A1': 10,
    'B1': 20,
    'C1': 30
}


yy = ['A1', 'B1', 'C1']

p = "sum(lst)"

eval(p, {'lst': yy}, ff)

我知道eval 的结果。我在到达 eval

之前过滤所有内容

最佳答案

你必须使用eval吗? ?

为什么不使用 sum() ;

yy = ['A1', 'B1', 'C1']

ff = {
    'A1': 10,
    'B1': 20,
    'C1': 30
}

print sum([ff[key] for key in yy])

如果你真的需要使用eval ,这里是怎么做的:

print eval('+'.join(str(ff[key]) for key in yy))
# or for short
print eval("+".join(yy), globals=ff)

# or the way you are doing
print eval("sum(lst)", {'lst': [ff[key] for key in yy]})

您收到 TypeError 的原因是因为"sum(lst)"本质上是 sum(['A1', 'B1', 'C1']) ,Python 不知道如何处理。通过更改 lst[ff[key] for key in yy]我们正在制作一个新列表,其中包含 yy 引用(按键)的数字在ff

我看到你的评论了:

I am using eval to parse Excel formulas like this one '=SUM(AY92:BI92)/SUM(AL92:AX92)' where I first expand the list from Ay92 to BI92 and then do a sum using eval

为什么不获取 AY92:BI92 的值?放入列表和 AL92:AX92 的值中进入第二个列表,他们使用 sum(lst1)/sum(lst2) ? eval 很讨厌,如果这个 excel 文件在单元格内部包含恶意代码,它就会运行。

关于python - 使用 eval 对列表求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32288942/

相关文章:

language-agnostic - 我什么时候应该使用 eval(获取一个字符串并在运行时将其作为代码执行)?

Python打包分发安装后步骤

python - numpy中两个二维数组的Numpy点积得到三维数组

c# - Newtonsoft Json.NET 可以跳过序列化空列表吗?

python - "TypeError: list indices must be integers or slices, not str"回归分析

javascript - eval 的最大字符串长度

eval - 在 sh 中获取 eval 命令的退出代码

javascript - Django CORS 访问控制允许来源丢失

python - 当只打开一个连接时,为什么 redis pub 和 sub 被认为是不同的客户端?

python - 将列表格式化为字符串 Python