Pergunta

A simple question: I have a namedtuple like so

RowSource = namedtuple("RowSource","parcel_id str_number pre_direct prefix street_name ...")

In total there are 16 names. And I have a tuple of length 16 I want to assign to the named tuple

t = (653,
526011,
'950',
None,
None,
'county road 999',
None,
None,
'tule',
'ca',
96134,
9225,
-121.400979,
41.877468,
'0101000020E610000080D8D2A3A9595EC0ADA415DF50F04440',
'0101000020E610000080D8D2A3A9595EC0ADA415DF50F04440')

What is the easiest way to do this? I mean, I don't go and do t[0],t[1] etc.

Foi útil?

Solução

Use the *args syntax to apply each item in t as a separate argument:

RowSource(*t)

Alternatively, use the namedtuple._make() class method:

RowSource._make(t)

The latter has a slightly more helpful TypeError exception message:

>>> from collections import namedtuple
>>> SampleTuple = namedtuple('Sample', 'foo bar baz')
>>> SampleTuple(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 4 arguments (3 given)
>>> SampleTuple._make((1, 2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 17, in _make
TypeError: Expected 3 arguments, got 2

The __new__() takes exactly 4 arguments (3 given) text while you clearly passed in only 2 throws some newer users of Python off, the namedtuple_make() class method is slightly more informative here.

Outras dicas

The easiest way would be this:

RowSource(*t)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top