Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of lists in to list of tuples, reordered

How 'pythonic-ly', do I turn this:

[[x1,y1], [x2,y2]]

Into:

[(x1,x2),(y1,y2)]
like image 401
Cyrus Cold Avatar asked Apr 14 '16 04:04

Cyrus Cold


Video Answer


2 Answers

Use a zip and unpacking operator.

>>> l = [['x1','y1'], ['x2','y2']]
>>> zip(*l)
[('x1', 'x2'), ('y1', 'y2')]
like image 183
Bhargav Rao Avatar answered Oct 27 '22 22:10

Bhargav Rao


Handled more case in give test case.

If there are items in list which have different length.

In [19]: a
Out[19]: [[1, 2], [3, 4], [5, 6], [7, 8, 9]]

In [20]: import itertools

In [21]: b = itertools.izip_longest(*a)

In [22]: list(b)
Out[22]: [(1, 3, 5, 7), (2, 4, 6, 8), (None, None, None, 9)]
like image 30
Vivek Sable Avatar answered Oct 27 '22 23:10

Vivek Sable