Bas*_*asj 6 python string loops immutability
在这里,我们s在循环时修改字符串:
s = 'hello'
for c in s:
s += c
print(s)
Run Code Online (Sandbox Code Playgroud)
它不会产生无限循环(它可以:我们在每次迭代中添加一个新字符!)。
多年来我就知道这一点,但我无法真正解释原因。这与字符串不变性有关还是无关?
执行时for c in s:,是否s在开始循环之前将原件复制到内存中?
我认为可能会产生无限循环的另一种情况,但它不会:
s = 'hello'
def f(x):
i = 0
while True:
try:
yield x[i]
except IndexError:
break
i += 1
for c in f(s):
s += c
print(s)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |