0

Let's say i have 2 lists in a list:

List = [[1,2,3], [4,5,6]]

If i wanted to transpose the two lists i would go like this:

NewList = zip (List[0], List[1])

in this case if i export the lists to a csv file using this:

with open("Transposed.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(NewList)

I will get this:

1 4
2 5
3 6

Now in a case where i have a large number of lists in the main list, and i would like to avoid manually adding every single one of them into the zip function, is there a way i can do a for loop to transpose all the lists in the main list? instead of going like this:

NewList = zip (List[0], List[1]), ......List[20])
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Mikey9191
  • 7
  • 1
  • 2

2 Answers2

2

Use iterable argument unpacking:

>>> data = [[1,2,3], [4,5,6]]
>>> list(zip(*data))
[(1, 4), (2, 5), (3, 6)]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0
import csv
data = [[1,2,3], [4,5,6]]

with open("Transposed.csv") as f:
    w = csv.writer(f)
    for row in zip(*data):
        w.writerow(list(map(str, row)))
jamylak
  • 128,818
  • 30
  • 231
  • 230