defaultdict 附加列表列表而不是列表?

defaultdict appending list of list rather than list?

我正在尝试在 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 的工作方式有问题吗? 提前谢谢你

Is there something wrong with my implementation or understanding how defaultdict works?

完全没有。您的代码完全按预期工作。创建了空列表的默认值,并且您 .append 该列表的单个元素:[1, 2, 3, 4, 5]。实际上,这与 defaultdict 根本无关。一个列表包含一个列表是完全没问题的。 .append将一个列表转换为另一个列表并不是什么特殊操作。它与附加任何其他元素(如 1'hello 相同)。您 .append 编辑的 整个 列表被认为是一个 单个 元素。

如果您想将可迭代对象的 元素 添加到您的列表中,您应该改用 list.extend

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

dd["one"].extend(l)