In python 3, I have a tuple Row
and a list A
:
Row = namedtuple('Row', ['first', 'second', 'third'])
A = ['1', '2', '3']
How do I initialize Row
using the list A
? Note that in my situation I cannot directly do this:
newRow = Row('1', '2', '3')
I have tried different methods
1. newRow = Row(Row(x) for x in A)
2. newRow = Row() + data # don't know if it is correct
You can do Row(*A)
which using argument unpacking.
>>> from collections import namedtuple
>>> Row = namedtuple('Row', ['first', 'second', 'third'])
>>> A = ['1', '2', '3']
>>> Row(*A)
Row(first='1', second='2', third='3')
Note that if your linter doesn't complain too much about using methods which start with an underscore, namedtuple
provides a _make
classmethod alternate constructor.
>>> Row._make([1, 2, 3])
Don't let the underscore prefix fool you -- this is part of the documented API for this class and can be relied upon to be there in all python implementations, etc...
The namedtuple Subclass has a method named '_make'. Inserting an Array (Python List) into a namedtuple Objects it's easy using the method '_make':
>>> from collections import namedtuple
>>> Row = namedtuple('Row', ['first', 'second', 'third'])
>>> A = ['1', '2', '3']
>>> Row._make(A)
Row(first='1', second='2', third='3')
>>> c = Row._make(A)
>>> c.first
'1'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.