首页 > 解决方案 > 将参数用作新创建变量名称的一部分

问题描述

我想知道是否有一种方法可以使用字符串自动创建变量,例如我有以下代码(在 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_priceprocessed_promotion并且processed_calendar该函数将返回这些列表。

但是,上面的代码不能像在 Python 中那样工作。我想知道我应该如何正确编写代码以实现相同的目标?

标签: python

解决方案


getattr(object, name, [default])
setattr(object, name, value)

要获取或设置通过字符串命名的变量的值,请酌情使用上述方法之一。然而,任何时候你使用用户输入,它都可能成为注入攻击的来源——用户可以使用你不希望他们使用的名称,但该名称是有效的,因此用户可以访问他们不应该访问的数据.

因此,通常建议使用用户输入作为您定义的字典的键。

dictionary = {
  'apple': 'my_value'
}

dictionary[user_input] = 'their_value'

推荐阅读