Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named tuples in a list

Tags:

python

I have the following list

a = [[a1, b1, c1, [d1, e1, f1],
     [a2, b2, c2, [d2, e2, f2],
     [a3, b3, c3, [d3, e3, f3]]

How can I make this into a list of named tuples such that

a[0].val1
>>> a1
a[1].val2
>>> b2
a[0].box
>>> [d1, e1, f1]
like image 737
kasperhj Avatar asked Jan 09 '13 08:01

kasperhj


People also ask

What are named tuples?

A named tuple is an extension and custom data type that enrich built-in tuples with extra utilities. They are very useful in context where we need to create a data structure that can be accessed by both the positional index and the named attribute of the elements.

What are named tuples used for?

In general, you can use namedtuple instances wherever you need a tuple-like object. Named tuples have the advantage that they provide a way to access their values using field names and the dot notation. This will make your code more Pythonic.

Where do you declare a named tuple?

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.

Can you have tuples in a list?

We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.


1 Answers

Use the collections.namedtuple class factory to create a named tuple class:

mynamedtuple = collections.namedtuple('mynamedtuple', ('val1', 'val2', 'val3', 'box'))

somenamedtuple = mynamedtuple('a1', 'a2', 'a3', ['d1', 'e1', 'f1'])
somenamedtuple.box  # returns ['d1', 'e1', 'f1']

You can convert your existing list using a list comprehension:

a = [mynamedtuple(*el) for el in a]
like image 130
Martijn Pieters Avatar answered Oct 09 '22 15:10

Martijn Pieters