基于输入参数的函数替换

2024-10-04 03:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有多个名为data_w1data_w2data_w3data_wn的列表。我有一个接受整数band作为输入的函数,我希望该函数只对相应的列表进行操作。你知道吗

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

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

但是执行上述操作并没有像预期的那样起作用,因为我得到的错误是没有定义任何带有wband的内容。我该怎么做?你知道吗


Tags: 函数字符串代码列表newdatabanddef
2条回答

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

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,2,…,n,那么一个整数i,你想要得到第i个列表,只需要有一个列表列表,并用整数i索引外部列表(在你的例子中称为band)。你知道吗

l = [data_w1, data_w2, data_w3]
list_to_operate_on = l[band]
func(list_to_operate_on)

相关问题 更多 >