[英]string not returned from function, but list is returned
I use a function to aggregate strings; 我使用一个函数来聚合字符串;
this function performs this concatenation via 2 different methods: 此函数通过两种不同的方法执行此串联:
1) via string concatenation : CUM_STR = CUM_STR + str(IDX) 1)通过字符串连接:CUM_STR = CUM_STR + str(IDX)
2) via List append : CUM_LST.append(IDX) 2)通过列表追加:CUM_LST.append(IDX)
When returning from this function, 从此函数返回时,
method 1 always gives an empty string for CUM1_TXT 方法1始终为CUM1_TXT提供空字符串
method 2 correcly aggregates strings in the CUM_LST List 方法2正确聚合CUM_LST列表中的字符串
Here is a sample of this case : 这是此情况的示例:
CUM1_TXT = ''
CUM1_LIST = []
def modif(IDX,CUM_STR,CUM_LST):
CUM_STR = CUM_STR + str(IDX)
CUM_LST.append(IDX)
print CUM_STR
print CUM_LST
return CUM_STR,CUM_LST
for INDEX in range(10):
modif(INDEX,CUM1_TXT,CUM1_LIST)
print CUM1_TXT,CUM1_LIST
By the way, the fact to code the CUM_STR and CUM_LST on the return statement does not change anything at the result 顺便说一句,在return语句上编写CUM_STR和CUM_LST的事实不会改变结果
Any help appreciated 任何帮助表示赞赏
let's take your method: 让我们采用您的方法:
def modif(IDX,CUM_STR,CUM_LST):
CUM_STR = CUM_STR + str(IDX)
CUM_LST.append(IDX)
print CUM_STR
print CUM_LST
return CUM_STR,CUM_LST
CUM_STR
is a str
object. CUM_STR
是一个str
对象。 It is immutable , so modif
cannot change the caller value. 它是不可变的 ,因此
modif
不能更改调用者的值。
CUM_LST
is a list
object. CUM_LST
是一个list
对象。 It is mutable . 这是可变的 。 Appending within the method affects the caller value (altough not very nice to modify parameters, caller may not expect it)
在方法中附加会影响调用方的值(虽然修改参数不是很好,但调用方可能不会期望它)
and to top it all, you're returning the values, but you don't assign them in the caller: return values are lost on function return. 最重要的是,您正在返回值,但没有在调用方中分配它们:函数返回时,返回值会丢失。 Performing a
return
on parameters does not change the parameters. 执行参数
return
不会更改参数。
If you allow me, I would rewrite it like this: 如果允许的话,我会这样重写:
def modif(IDX,CUM_STR,CUM_LST):
return CUM_STR + str(IDX),CUM_LST+[IDX]
and you'd have to call it like this: 而且您必须这样称呼它:
CUM1_TXT,CUM1_LIST = modif(INDEX,CUM1_TXT,CUM1_LIST)
You are discarding the return value of modif function, replace the call to modif with this line: 您将舍弃modif函数的返回值,用以下行替换对modif的调用:
CUM1_TXT, _ = modif(INDEX,CUM1_TXT,CUM1_LIST) CUM1_TXT,_ = modif(INDEX,CUM1_TXT,CUM1_LIST)
Note that "_" is Python common practice to call variable which will not be used 请注意,“ _”是Python常用的调用变量的惯用方法
C C
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.