【发布时间】:2017-11-03 20:47:18
【问题描述】:
我正在尝试在 python 3 中使用 collections.defaultdict。 我在控制台中尝试了以下步骤:
>>> from collections import defaultdict
>>> l = [1,2,3,4,5]
>>> dd = defaultdict(list)
>>> dd["one"].append(l)
>>> print(dd)
defaultdict(<class 'list'>, {'one': [[1, 2, 3, 4, 5]]})
你可以看到它添加了[[1, 2, 3, 4, 5]],即列表列表,所以我需要两个 for 循环来读取它的变量。
为什么它不附加 [1, 2, 3, 4, 5]?? 之类的东西?
我的实现或理解 defaultdict 的工作原理是否有问题? 提前谢谢你
【问题讨论】:
-
append将您传入的对象添加到列表中,我认为您想使用extend -
感谢@RNar,它成功了。你能把你的评论放在答案中吗?我会赞成的
标签: python python-3.x collections defaultdict