python - 关于python中递归dict创建的问题
问题描述
我在网上看到了这段代码:
class StreamChecker(object):
def __init__(self, words):
"""
:type words: List[str]
"""
print(words)
self.waitlist = []
self.trie = dict()
for word in words:
temp_dict = self.trie
for letter in word:
temp_dict = temp_dict.setdefault(letter, dict())
temp_dict['#'] = '#'
if __name__ == '__main__':
a = StreamChecker(['abc', 'wef', 'ykj'])
print(a.trie)
启动后,打印self.trie
得到{'a': {'b': {'c': {'#': '#'}}}, 'w': {'e': {'f': {'#': '#'}}}, 'y': {'k': {'j': {'#': '#'}}}}
我'temp_dict = temp_dict.setdefault(letter, dict())'
对代码中的这一行感到困惑。由于每次setdefault
都会返回一个空字典{}
,为什么self.trie
每次都更改,因为setdefault
只用于空字典?据我了解,self.trie
每次只会更改一次word
,self.trie
应该像{'a': {}, 'w': {}, 'y': {}}
谁可以给我解释一下这个?谢谢
解决方案
>>> help(dict.setdefault)
setdefault(self, key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
一个空字典不一定与另一个空字典是同一个对象。发生的事情是这条线
temp_dict = temp_dict.setdefault(letter, dict())
是首先向当前添加一个新键temp_dict
(对应的值是一个空字典),然后返回对该新添加值的引用。当它在循环中运行时,它最终会递归地将新字典添加到原始字典(即self.trie
)中。
dict
因为我们正在修改的嵌套包含在 中self.trie
,所以我们可以看到我们的更改反映在 中self.trie
。
分解此语句可能会有所帮助:
temp_dict = temp_dict.setdefault(letter, dict())
进入这个:
if letter not in temp_dict:
temp_dict[letter] = dict() # create a new dict, and put it inside the current dict
temp_dict = temp_dict[letter] # jump inside the new dict that we just created,
# or the existing dict that was there if it already existed.
推荐阅读
- c# - Oracle 更新命令在 C# 中总是返回 0
- c# - MainWindow 完成后运行测试代码
- spring-boot - 内容被附加到通过 JPA 脚本生成生成的 DDL 文件中,而不是被替换
- c# - 时间:2019-04-10 标签:c#casting child class SOAP
- hyperledger-composer - Hyperledger Composer 事务处理器函数中如何处理“long”类型的整数?
- admin-on-rest - 仅允许在编辑/创建中创建新的 ArrayInput 元素并使现有元素不可变/仅显示
- c# - 使用 c# 使用 sha256 进行数字签名
- flutter - 我有一个带有滚动表单的部分,但滚动无法正常工作
- date - 让 CakePHP 3 以 yyyy-mm-dd 格式输出日期
- javascript - 如何遍历jquery数组中提供的变量变量?