Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swap rows and columns with list comprehension

Here is what I got …

>>> v = [[x for x in range(4)] for x in range(4)]
>>> h = [[x for x in range(4)] for x in range(4)]
>>> v
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
>>> for i in range(len(v[0])):
>>>    for j in range(len(v[0])):
>>>        h[j][i] = v[i][j]
...        
>>> h
[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]

How can I generate h with list comprehension instead of the nested for loops?

UPDATE:

Thank you all for your awesome answers and I apologize for not being more clear in my original post. I should have initialized v like so:

>>> v = [[randint(0,10) for x in range(4)] for x in range(4)]

For instance v is:

>>> v
[[5, 1, 0, 5], [8, 9, 9, 10], [3, 7, 1, 1], [6, 6, 10, 7]]
>>> for i in range(len(v[0])):
>>>    for j in range(len(v[0])):
>>>        h[j][i] = v[i][j]
...     
>>> h
[[5, 8, 3, 6], [1, 9, 7, 6], [0, 9, 1, 10], [5, 10, 1, 7]]
like image 428
Red Cricket Avatar asked Dec 28 '25 19:12

Red Cricket


2 Answers

Instead of a list comprehension, you can zip:

list(map(list,zip(*v)))

# [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]

If it's ok to have a list of tuples, you can omit the map:

list(zip(*v))
# [(0, 0, 0, 0), (1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3)]
like image 99
sacuL Avatar answered Dec 31 '25 08:12

sacuL


if you must use list comprehensions:

[[y for x in range(4)] for y in range(4)]
like image 22
Yakov Dan Avatar answered Dec 31 '25 08:12

Yakov Dan