python - 将参数用作新创建变量名称的一部分
问题描述
我想知道是否有一种方法可以使用字符串自动创建变量,例如我有以下代码(在 Python 中不能正常工作):
def function(lst1, string1):
lst2 = 'processed_' + string1
lst2 = [] #here I created a string called lst2, but I want to use the string as the variable name.
for i in range(len(lst1)):
if abs(lst1[i]) >= 0.0001 :
lst2.append(i)
return lst2
function(list1, 'price') # list1 is a list which contains the index for column numbers, e.g., [1,2,3]
function(list1, 'promotion')
function(list1, 'calendar')
我希望使用该函数能够创建诸如 、 和 之类的列表processed_price
,processed_promotion
并且processed_calendar
该函数将返回这些列表。
但是,上面的代码不能像在 Python 中那样工作。我想知道我应该如何正确编写代码以实现相同的目标?
解决方案
getattr(object, name, [default])
setattr(object, name, value)
要获取或设置通过字符串命名的变量的值,请酌情使用上述方法之一。然而,任何时候你使用用户输入,它都可能成为注入攻击的来源——用户可以使用你不希望他们使用的名称,但该名称是有效的,因此用户可以访问他们不应该访问的数据.
因此,通常建议使用用户输入作为您定义的字典的键。
dictionary = {
'apple': 'my_value'
}
dictionary[user_input] = 'their_value'
推荐阅读
- mysql - mySQL - 1067 - 'updated_at' 的默认值无效
- java - httpclient 提供不同的结果
- php - PHP $_POST 没有收到数据
- python - Postgresql 更新原因:'django.db.utils.OperationalError: could not access file "$libdir/postgis-2.4": No such file or directory'
- spring-security-oauth2 - 在重定向之前在标头中设置令牌
- python - 函数返回列表中有多少个整数元素是同一列表中其他元素的精确平方
- sql - 在 PrestoDB 中提取凌乱的 JSON 值
- http2 - 我可以通过 STDIN/STDOUT 说 HTTP/2 吗?
- c# - 获取地面点的射线无法获取地面点
- ms-access-2016 - 用表单更新两个表