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]]
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)]
if you must use list comprehensions:
[[y for x in range(4)] for y in range(4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With