merge list of tuples with list
Peter Otten
__peter__ at web.de
Wed Oct 20 04:29:26 EDT 2010
Daniel Wagner wrote:
> Hello Everyone,
>
> I'm new in this group and I hope it is ok to directly ask a question.
>
> My short question: I'm searching for a nice way to merge a list of
> tuples with another tuple or list. Short example:
> a = [(1,2,3), (4,5,6)]
> b = (7,8)
>
> After the merging I would like to have an output like:
> a = [(1,2,3,7), (4,5,6)]
>
> It was possible for me to create this output using a "for i in a"
> technique but I think this isn't a very nice way and there should
> exist a solution using the map(), zip()-functions....
>
> I appreciate any hints how to solve this problem efficiently.
>>> from itertools import starmap, izip
>>> from operator import add
>>> a = [(1,2,3), (4,5,6)]
>>> b = (7,8)
>>> list(starmap(add, izip(a, izip(b))))
[(1, 2, 3, 7), (4, 5, 6, 8)]
This is likely slower than the straightforward
[x + (y,) for x, y in zip(a, b)]
for "short" lists, but should be faster for "long" lists. Of course you'd
have to time-it to be sure.
You should also take into consideration that the latter can be understood
immediately by any moderately experienced pythonista.
Peter
More information about the Python-list
mailing list