用列表理解交换行和列

时间:2018-12-04 07:18:45

标签: python list-comprehension

这就是我得到的……

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

如何使用列表推导而不是嵌套的for循环生成h?

更新:

谢谢大家的出色回答,对于我在原始帖子中不清楚的内容,我深表歉意。我应该像这样初始化v

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

例如v是:

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

3 个答案:

答案 0 :(得分:3)

您可以zip来代替列表理解:

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

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

如果可以使用元组列表,则可以省略map

list(zip(*v))
# [(0, 0, 0, 0), (1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3)]

答案 1 :(得分:1)

如果您必须使用列表推导:

[[y for x in range(4)] for y in range(4)]

答案 2 :(得分:1)

直接的理解:

h = [ v[j][i] for i in range(4) for j in range(4)  ]