### Transpose of list of list

82 观看

3回复

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)):
...     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.

### 回应 3

11

170611 作者的声誉

You swap `l` with `l`... and then when you get to `l`, you swap `l` with `l`. 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` with `a`, because there is no `a`.

0

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)):
a2[i][j] = a[j][i]

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

print(a)
print(a2)
print(a3)
``````

1

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

print(transposed)
# [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
``````