来自 MATLAB 背景并希望对以下行为进行一些澄清:
在列表列表上循环时,循环变量似乎在循环内受到影响:
foo = [['string1'],['string2'],['string3']]
for item in foo:
item.append('test')
print(foo)
[['string1', 'test'], ['string2', 'test'], ['string3', 'test']]
为什么在附加 foo
时 item
会更新?
同样,为什么有些方法需要分配输出而其他方法不需要?例如在列表上,您可以简单地附加:
list.append(new_item)
但是对于字符串,输出需要赋值:
string = string.replace('old','new')
答案 0 :(得分:0)
您可以使用 x = int/float/str(134324) '重新输入' 这里有示例:
x_int = 13
print(type(x_int))`
y_str = ('d')
print(type(y_str))
print('and here we can change type')
x_str = str(13)
print(type(x_str))
y_int = int('d')
#You can retype just something.
#you can retype int into float
#you can retype int and float into string
#you CANT retype string into float or int
答案 1 :(得分:0)
我在 Python 中找到了有关副本和引用的答案。有关此线程的更多信息:
python: changes to my copy variable affect the original variable
来自@juanpa.arrivill 的引用:
https://nedbatchelder.com/text/names.html
谢谢/