opposite of zip()?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Dec 15 01:46:44 EST 2007
On Fri, 14 Dec 2007 21:47:06 -0800, igor.tatarinov wrote:
> Given a bunch of arrays, if I want to create tuples, there is
> zip(arrays). What if I want to do the opposite: break a tuple up and
> append the values to given arrays:
> map(append, arrays, tupl)
> except there is no unbound append() (List.append() does not exist,
> right?).
Don't guess, test.
>>> list.append # Does this exist?
<method 'append' of 'list' objects>
Apparently it does. Here's how *not* to use it to do what you want:
>>> arrays = [[1, 2, 3, 4], [101, 102, 103, 104]]
>>> tupl = tuple("ab")
>>> map(lambda alist, x: alist.append(x), arrays, tupl)
[None, None]
>>> arrays
[[1, 2, 3, 4, 'a'], [101, 102, 103, 104, 'b']]
It works, but is confusing and hard to understand, and the lambda
probably makes it slow. Don't do it that way.
> Without append(), I am forced to write a (slow) explicit loop:
> for (a, v) in zip(arrays, tupl):
> a.append(v)
Are you sure it's slow? Compared to what?
For the record, here's the explicit loop:
>>> arrays = [[1, 2, 3, 4], [101, 102, 103, 104]]
>>> tupl = tuple("ab")
>>> zip(arrays, tupl)
[([1, 2, 3, 4], 'a'), ([101, 102, 103, 104], 'b')]
>>> for (a, v) in zip(arrays, tupl):
... a.append(v)
...
>>> arrays
[[1, 2, 3, 4, 'a'], [101, 102, 103, 104, 'b']]
I think you're making it too complicated. Why use zip()?
>>> arrays = [[1, 2, 3, 4], [101, 102, 103, 104]]
>>> tupl = tuple("ab")
>>> for i, alist in enumerate(arrays):
... alist.append(tupl[i])
...
>>> arrays
[[1, 2, 3, 4, 'a'], [101, 102, 103, 104, 'b']]
--
Steven
More information about the Python-list
mailing list