【问题标题】:How to define list of int and defaultdict如何定义 int 和 defaultdict 列表
【发布时间】:2013-02-08 03:32:28
【问题描述】:

我想在 python 中定义一个整数和 defaultdict 的列表。 我正在创建一个将返回上述列表的父字典。

我无法定义列表类型。

def index_struct():return defaultdict(list_struct)
def list_struct(): return list(int,post_struct)
def post_struct(): return defaultdict(list)

当前出现错误,因为列表不能接受两个参数..

提前感谢您的帮助

【问题讨论】:

  • 你为什么要创建类型?
  • 只使用索引应该很容易访问它们

标签: python list dictionary function


【解决方案1】:

你说得对,list() 只接受一个参数。请改用方括号表示法。另请注意,[int, post_struct] 不起作用,因为没有调用这两个构造函数。您需要通过添加括号手动调用构造函数:

from collections import defaultdict

def index_struct():return defaultdict(list_struct)
def list_struct(): return [int(), post_struct()]
def post_struct(): return defaultdict(list)

>>> d = index_struct()
>>> d['somekey'][0] = 5
>>> d['somekey'][1]['anotherkey'] = 6
>>> d
defaultdict(<function list_struct at 0x10252ff50>, {'somekey': [5, defaultdict(<type 'list'>, {'anotherkey': 6})]})

【讨论】:

  • int() 不只是说0 的慢方式吗?
  • 是的 :-) 也就是说,我尽可能地反映了 OP 的方法,以便他可以看到他的错误在哪里(即构造函数没有被调用)。与原始帖子相比,预先计算 int() 会使答案更难理解。
  • 嘿,谢谢。我错了。没有调用构造函数。还有一个疑问,什么时候定义结构类型更好,什么时候使用类来代替
猜你喜欢
  • 2023-03-26
  • 2013-11-21
  • 2012-06-03
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多