dict.clear()和Python分配{}之间的区别 [英] Difference between dict.clear() and assigning {} in Python

查看:139
本文介绍了dict.clear()和Python分配{}之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,调用 clear()并将 {} 分配给字典之间有区别吗?如果是,是什么?
示例:

In python, is there a difference between calling clear() and assigning {} to a dictionary? If yes, what is it? Example:

d = {"stuff":"things"}
d.clear()   #this way
d = {}      #vs this way

推荐答案

也指同一个字典,有很大的区别:

If you have another variable also referring to the same dictionary, there is a big difference:

>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}

这是因为分配 d = {} 创建一个新的空字典,并将其分配给 d 变量。这将留下 d2 ,指向旧字典,其中仍有项目。但是, d.clear()清除与 d d2 都指向。

This is because assigning d = {} creates a new, empty dictionary and assigns it to the d variable. This leaves d2 pointing at the old dictionary with items still in it. However, d.clear() clears the same dictionary that d and d2 both point at.

这篇关于dict.clear()和Python分配{}之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆