为什么python的字典迭代似乎与副本一起工作?

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",为什么不设置?

Emi*_*nov 7

这与字符串或列表无关.魔鬼是如何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)


Sve*_*ach 5

这条线上唯一的东西

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)

  • 这与字符串不可变无关; 如果我替换"你好":"精彩"`与`"你好":[1,2]`它的工作方式相同. (2认同)