Transpose of list of list
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.作者: Adorn 的来源 发布者: 2017 年 12 月 27 日
l... and then when you get to
l, you swap
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, because there is no
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.
作者: Amos Egel 发布者: 27.12.2017 06:09
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)
You could also just use a basic list comprehension here:
作者: RoadRunner 发布者: 28.12.2017 02:58
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]]