为什么Python的字典迭代似乎可以与副本一起使用?

发布于 2024-11-28 20:07:27 字数 294 浏览 4 评论 0原文

我很困惑 python 如何迭代这本字典。从 python 的文档来看,itervalues 返回字典值的迭代器。

dict = {"hello" : "wonderful", "today is" : "sunny", "more text" : "is always good"}

for x in dict.itervalues():
    x = x[2:]   

print dict

这会原封不动地打印出原始词典。这是为什么?如果我说位置 x 的值是“blabla”,为什么它没有被设置?

I am confused how python is iterating through this dictionary. From python's documentation, the itervalues returns an iterator over the dictionary's values.

dict = {"hello" : "wonderful", "today is" : "sunny", "more text" : "is always good"}

for x in dict.itervalues():
    x = x[2:]   

print dict

This prints out the original dictionary unchanged. Why is that? If I am saying the value at position x is "blabla", why is it not getting set?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寂寞陪衬 2024-12-05 20:07:27

这与字符串或列表无关。问题在于 for 的展开方式。

for x in d.iteritems():
    # loop body

或多或少相当于做

iter = d.itervalues()
while True:
    try:
        x = next(iter)
        # loop body
    except StopIteration:
        break

所以考虑到这一点,不难看出我们只是重新分配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

This has nothing to do with strings or lists. The devil is in how the for is unfolded.

Doing

for x in d.iteritems():
    # loop body

is more-or-less equivalent to doing

iter = d.itervalues()
while True:
    try:
        x = next(iter)
        # loop body
    except StopIteration:
        break

So with this in mind it's not very hard to see that we are just reassigning x, which holds a result from a function call.

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
儭儭莪哋寶赑 2024-12-05 20:07:27

该行所做的唯一事情

x = x[2:]

是创建字符串切片 x[2:] 并重新绑定名称 x 以指向这个新字符串。它不会更改之前指向的字符串x。 (字符串在Python中是不可变的,它们不能被更改。)

为了实现你真正想要的,你需要使字典条目指向由切片创建的新字符串对象:

for k, v in my_dict.iteritems():
    my_dict[k] = v[2:] 

The only thing the line

x = x[2:]

does is creating the string slice x[2:] and rebinding the name x to point to this new string. It does not change the string x pointed to before. (Strings are immutable in Python, they can't be changed.)

To achieve what you actually want, you need to make the dictionary entry point to the new string object created by the slicing:

for k, v in my_dict.iteritems():
    my_dict[k] = v[2:] 
独行侠 2024-12-05 20:07:27

正如 Sven Marnach 点出,字符串是不可变的,您只需将 x 重新绑定到由切片表示法创建的新字符串。您可以使用 id 来证明 x 确实 指向字典中的同一对象:

>>> obj = 'hello'

>>> id(obj)
<<< 4318531232

>>> d = {'key': obj}   

>>> [id(v) for v in d.values()]
<<< [4318531232]

>>> [id(v) for v in d.itervalues()]
<<< [4318531232]

>>> [(k, id(v)) for k, v in d.items()]
<<< [('key', 4318531232)]

>>> [(k, id(v)) for k, v in d.iteritems()]
<<< [('key', 4318531232)]

您可以使用 iteritems一起迭代键和值来执行您想要的操作:

for k,v in dict.iteritems():
    dict[k] = v[2:]

As Sven Marnach points out, strings are immutable and you are just rebinding x to a new string created by the slice notation. You can demonstrate that x does point to the same object in the dictionary by using id:

>>> obj = 'hello'

>>> id(obj)
<<< 4318531232

>>> d = {'key': obj}   

>>> [id(v) for v in d.values()]
<<< [4318531232]

>>> [id(v) for v in d.itervalues()]
<<< [4318531232]

>>> [(k, id(v)) for k, v in d.items()]
<<< [('key', 4318531232)]

>>> [(k, id(v)) for k, v in d.iteritems()]
<<< [('key', 4318531232)]

You can use iteritems to iterate over key and value together to do what you want:

for k,v in dict.iteritems():
    dict[k] = v[2:]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文