根据输入参数替换功能

时间:2018-08-07 20:31:33

标签: python python-3.x function substitution

说我有多个名为data_w1data_w2data_w3,...,data_wn的列表。我有一个函数,需要一个整数band作为输入,我希望该函数只能在相应的列表上进行操作。

我熟悉字符串替换,但是在这里我不处理字符串,那么我该怎么做呢?一些伪代码:

def my_function(band):
    wband_new = []
    for entry in data_wband:
        # do stuff
        wband_new.append( #new stuff )
    return wband_new

但是执行上述操作无法按预期方式进行,因为我收到以下错误:未定义带有wband的任何内容。我该怎么办?

2 个答案:

答案 0 :(得分:0)

假设在函数之前的脚本中有data变量。您需要做的是将data_wband替换为globals()['data_w'+str(band)]

data_w1 = [1,2,3]
data_w2 = [4,5,6]

def my_function(band):
    wband_new = []
    for entry in globals()['data_w'+str(band)]:
        # do stuff
        wband_new.append( #new stuff )
    return wband_new

答案 1 :(得分:0)

不确定要问的是什么,但是如果要包含列表1、2,...,n,则为整数i,并且要获取第i个列表,只需列出一个列表,然后用整数i(在您的情况下称为band)索引外部列表。

l = [data_w1, data_w2, data_w3]
list_to_operate_on = l[band]
func(list_to_operate_on)
相关问题