0

My input is

tbl_ports = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]

And my expected output is

[[1,5,9], [2,6,10], [3,7,11], [4,8,12]]

My limit was to do the following to create the output reorder_list

reorder_list = []
for i in range(len(tbl_ports)):
    for col in tbl_ports:
        reorder_list.append(col[i])
reorder_list=[1, 5, 9, 2, 6, 10, 3, 7, 11]

How can I contain them in a list of 3 elements?

tmhs
  • 998
  • 2
  • 14
  • 27

2 Answers2

1

To fix the code that you already have, you need to create a new list every time a row is complete, such as:

reorder_list = []
for i in range(len(tbl_ports)):
    reorder_list.append([])
    for col in tbl_ports:
        reorder_list[-1].append(col[i])

Which would yield the following result:

[[1, 5, 9], [2, 6, 10], [3, 7, 11]]

You can also use a more pythonic method of solving the problem,

list(zip(*tbl_port))

Which would yield a list of tuples:

[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

If you want a list of lists, then you can simply just use list comprehension:

[list(e) for e in zip(*tbl_port)]

Edit:

for an explanation of why zip(*list) works, you need to know what zip does.

zip is a function in python that takes in multiple lists, and outputs a generator of lists for each element in every corresponding list. So zip([1, 2, 3], [4, 5, 6]) would yield [(1, 4), (2, 5), (3, 6)].

the * basically expands the input into multiple positional arguments, where function(*[1, 2, 3, 4]) is equivalent to function(1, 2, 3, 4)

So the code passed in the input array as a list of arguments to the zip function, which then outputs the result in the order that you want.

The only remaining problem is that zip generates a generator instead of an actual list.

To solve that problem, simply call the list function on a generator to convert it into a list, or pass it in a list comprehension to yield the desired result.

Jimmy Ding
  • 24
  • 3
  • Thank you for explaining the details. I was wondering why the results produces tuples and what's actually happening with zip, *. It is my first time introduced to zip, it looks very useful. – tmhs Apr 24 '20 at 15:51
1

This is exactly what the zip() function is for.

list(zip([1,2,3,4],'abcd'))

You can use the unpack syntax " * " to make python unpack your lists to the zip function.

tbl_ports    = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
reorder_list = list(zip(*tbl_ports))
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15