Reputation: 7032
I have defined structure which looks like this. Basically a name value pair
from collections import namedtuple
CP = namedtuple('Cell', ['attr', 'value'])
This fits into a larger ordered structure which looks like this
_structure = [CP('id', None), CP('name', None)]
Then I get a series of results which correspond to three instances of _structure
results = [(1,'foo'),(2,"bar"),(3,"zaz")]
How do I map
these into the following:
final = [[CP('id', 1), CP('name', "foo")],
[CP('id', 2), CP('name', "bar")],
[CP('id', 3), CP('name', "zaz")],]
Upvotes: 1
Views: 76
Reputation: 95242
I'd use a list comprehension:
final = [[CP('id', ident), CP('name', name)] for (ident,name) in results]
But you mentioned map
, which you can also use:
final = map(lambda (ident,name): [CP('id',ident),CP('name',name)], results)
(Note that I didn't name the id variable id
because that conflicts with an existing global function in Python.)
In Python, comprehensions/generators are generally preferred over map
, because they're more general and arguably more legible. Admittedly, the relative lack of generality in map
is largely because Python's lambda
construct for creating anonymous functions is rather limited compared to what's available in more functional languages, where map
and friends reign supreme.
Upvotes: 1