Home > Blockchain >  How to transpose a 2D-list into a column view?
How to transpose a 2D-list into a column view?

Time:11-09

I have this 2D-list

[["a1", "b1", "c1"], ["a2", "b2", "c2"]]

That I want to transpose to a column-view. Each inner list has the same size.

Expected result :

[['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]

I'm looking for a one-liner answer.

I've tried the code below that works but needs one line to initialize the l_col variable and two for the loop.

l = [["a1", "b1", "c1"], ["a2", "b2", "c2"]]

l_col = []
for i in range(len(l[0])):
    l_col.append([x[i] for x in l])

print(l_col)  # [['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]

Thanks for your help.

CodePudding user response:

In newer versions of Python, you can use:

A           = [["a1", "b1", "c1"], ["a2", "b2", "c2"]]
A_transpose = list(map(list,zip(*A)))

print('A_transpose: ', A_transpose)

# output:
#     A_transpose:  [['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]

PS. For many applications, list(zip(*A)) also works. However, this short command returns tuples in the inner dimension: [('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2')]. In the code above, we corrected this issue by introducing map(list,...).

CodePudding user response:

[[x[i] for x in l] for i in range(len(l[0]))]
  • Related