【问题标题】:namedtuple takes 3 arguments? [duplicate]namedtuple 需要 3 个参数? [复制]
【发布时间】:2018-05-04 19:15:54
【问题描述】:

尝试在 Python3 Jupyter notebook 中运行此代码:

t = namedtuple('a', 'b')
a = [1,0,1]
b = [1,1,1]
Out, In = np.asanyarray(a), np.asanyarray(b)
t(Out.shape[0], *In.shape)

返回错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-151-7955ff03a60d> in <module>()
      3 b = [1,1,1]
      4 Out, In = np.asanyarray(a), np.asanyarray(b)
----> 5 t(Out.shape[0], *In.shape)

TypeError: __new__() takes 2 positional arguments but 3 were given

是否可以使用两个参数创建命名元组?

更新:

为什么这不会导致类似的问题:

t = namedtuple('ps', 'Out In S')

a = np.asanyarray([[1]])
b  = np.asanyarray([[1]])

d = t(a.shape[0], *b.shape)

d

计算:

ps(Out=1, In=1, S=1)

更新 2:

我想我现在明白了 namedtuple('ps', 'Out In S') 转换为 namedtuple('name_of_tuple', 'tuple_values_seperated_by_spaces')

【问题讨论】:

标签: python python-3.x namedtuple


【解决方案1】:

命名元组构造函数的第一个参数是typename:命名元组的名称,而不是参数。 [documentation]

所以你应该将t构造为:

#                   v parameters
t = namedtuple('t', ('a', 'b'))
#              ^ type name

为了更方便,你还可以提供一个空格分隔的参数字符串。所以等价的是:

#t = namedtuple('t', 'a b')
#                    ^ space separated list of parameters

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2013-07-26
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多