What I learned today

Peter Otten __peter__ at web.de
Sat Feb 15 08:46:09 EST 2020


Stefan Ram wrote:

> The other thing I read in a book. I already knew that one
> can zip using ... »zip«. E.g.,
> 
> x =( 'y', 'n', 'a', 'n', 't' )
> y =(   4,   2,   7,  3,    1 )
> z = zip( x, y )
> print( list( z ))
> [('y', 4), ('n', 2), ('a', 7), ('n', 3), ('t', 1)]
> 
> But the book told me that you can unzip using ... »zip« again!
> 
> z = zip( x, y )
> a, b = zip( *z )
> print( a )
> ('y', 'n', 'a', 'n', 't')
> print( b )
> (4, 2, 7, 3, 1)
> 
> Wow!
> 

Another way to look at that is that if you write a matrix as a tuple of 
tuples

>>> a = (1,2), (3,4), (5,6)

you can transpose it with

>>> def transposed(a):
...     return tuple(zip(*a))
... 
>>> transposed(a)
((1, 3, 5), (2, 4, 6))

and transposing twice gives the original matrix:

>>> transposed(transposed(a)) == a
True




More information about the Python-list mailing list