Cyrus Cold
Cyrus Cold

Reputation: 279

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)]

Upvotes: 6

Views: 138

Answers (2)

Vivek Sable
Vivek Sable

Reputation: 10223

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)]

Upvotes: 2

Bhargav Rao
Bhargav Rao

Reputation: 52101

Use a zip and unpacking operator.

>>> l = [['x1','y1'], ['x2','y2']]
>>> zip(*l)
[('x1', 'x2'), ('y1', 'y2')]

Upvotes: 10

Related Questions