我无法使用return
函数来打印最终值。我的代码:
def filter_wave(wave,n):
new_wave = [i for i in wave]
for k in range(n):
for i in range(len(wave)):
curr_wave = new_wave.copy()
if(i==0):
new_wave[i] = int(curr_wave[i]*0.6+curr_wave[i+1]*0.2)
elif(i>0 and i<len(wave)-1):
new_wave[i] = int(curr_wave[i-1]*0.2+curr_wave[i]*0.6+curr_wave[i+1]*0.2)
else:
new_wave[i] = int(curr_wave[i-1]*0.2+curr_wave[i]*0.6)
print(new_wave)
迭代n
次之后,它应该返回最后一波。 print()
有效,但如果我尝试return
,则无效。有什么错误吗?
答案 0 :(得分:0)
如果我正确理解了您的问题,那么您可以通过运行以下行来调用函数
filter_wave(original_wave_sample, 200)
您希望输出等于打印变量new_wave
当您在主体中使用print()打印变量并且没有return语句时,该变量将被打印到屏幕上。如果使用return(new_wave),则必须指定一个变量,将在其中存储返回的变量new_wave:
函数中包含return(new_wave)
result = filter_wave(original_wave_sample, 200)
print(result)
完整示例:
def filter_wave(wave,n):
new_wave = [i for i in wave]
for k in range(n):
for i in range(len(wave)):
curr_wave = new_wave.copy()
if(i==0):
new_wave[i] = int(curr_wave[i]*0.6+curr_wave[i+1]*0.2)
elif(i>0 and i<len(wave)-1):
new_wave[i] = int(curr_wave[i-1]*0.2+curr_wave[i]*0.6+curr_wave[i+1]*0.2)
else:
new_wave[i] = int(curr_wave[i-1]*0.2+curr_wave[i]*0.6)
return(new_wave)
result = filter_wave(original_wave_sample, 200)
print(result)