Jus*_*tin 7 python iterator copy items
我很困惑python如何迭代这本词典.从python的文档中,itervalues返回字典值的迭代器.
dict = {"hello" : "wonderful", "today is" : "sunny", "more text" : "is always good"}
for x in dict.itervalues():
x = x[2:]
print dict
Run Code Online (Sandbox Code Playgroud)
这会打印出原始字典不变.这是为什么?如果我说位置x的值是"blabla",为什么不设置?
这与字符串或列表无关.魔鬼是如何for展开的.
干
for x in d.iteritems():
# loop body
Run Code Online (Sandbox Code Playgroud)
做得或多或少等同于做
iter = d.itervalues()
while True:
try:
x = next(iter)
# loop body
except StopIteration:
break
Run Code Online (Sandbox Code Playgroud)
因此,考虑到这一点,我们不难看出我们只是重新分配x,它保存了函数调用的结果.
iter = d.itervalues()
while True:
try:
x = next(iter)
x = 5 # There is nothing in this line about changing the values of d
except StopIteration:
break
Run Code Online (Sandbox Code Playgroud)
这条线上唯一的东西
x = x[2:]
Run Code Online (Sandbox Code Playgroud)
是创建字符串切片x[2:]并重新绑定名称x以指向此新字符串.它不会更改x之前指向的字符串.(字符串在Python中是不可变的,它们不能被更改.)
要实现您真正想要的,您需要使字典入口指向切片创建的新字符串对象:
for k, v in my_dict.iteritems():
my_dict[k] = v[2:]
Run Code Online (Sandbox Code Playgroud)