Transpose of list of list

python python-3.x

82 观看


1353 作者的声誉

I am just playing along with python to understand the things in more depth.

I learned that One of the easier ways is to use zip, but how about this:

>>> a = [[1,1,1], [2,2,2], [3,3,3]]
>>> for i in range(len(a)):
...   for j in range(len(a[0])):
...     a[i][j], a[j][i] = a[j][i], a[i][j]
>>> a
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]

well, I was expecting the answer to be

[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

because that is what Transpose would be ? I swapped the elements, right?? Also, this way was more natural to me. I read the documentation for zip here and it does not say anything about such "tricks". How to learn these more pythonic ways of doing the things? I am aware that asking for resources to learn goes into subjective choices and SO does not encourage such questions. But IMO, it is clearly not a matter of choice in this case, but finding any and every resource where such information is available.

作者: Adorn 的来源 发布者: 2017 年 12 月 27 日

回应 (3)


170611 作者的声誉


You swap l[0][1] with l[1][0]... and then when you get to l[1][0], you swap l[1][0] with l[0][1]. Every pair of elements gets swapped twice, except for the diagonal elements, but those get swapped with themselves anyway. Everything ends up back where it started.

If you want to perform a transpose by element swaps, you need to avoid swapping pairs twice:

for i in range(len(a)):
    for j in range(i+1, len(a)):
        a[i][j], a[j][i] = a[j][i], a[i][j]

Also, your transpose implicitly assumes square input. If you get a 3x5 input, you can't swap a[2][4] with a[4][2], because there is no a[4][2].

作者: user2357112 发布者: 27.12.2017 06:00


401 作者的声誉

The problem is that you are overwriting a during your loop, such that after the first transpose operation, the second just undoes the first.

You could either make a copy of a (and not overwrite a), or do it by a list comprehension.

import copy
a = [[1,1,1], [2,2,2], [3,3,3]]
a2  = copy.deepcopy(a)
for i in range(len(a)):
  for j in range(len(a[0])):
    a2[i][j] = a[j][i]

a3 = [[a[j][i] for j, _ in enumerate(ai)] for i, ai in enumerate(a)]

作者: Amos Egel 发布者: 27.12.2017 06:09


12708 作者的声誉

You could also just use a basic list comprehension here:

a = [[1,1,1], [2,2,2], [3,3,3]]

transposed = [[x[i] for x in a] for i in range(len(a[0]))]

# [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
作者: RoadRunner 发布者: 28.12.2017 02:58