6

Start with a list of strings. Each string will have the same number of characters, but that number is not predetermined, nor is the unrelated total number of strings.

Here is an example:

data = ['ABC', 'EFG', 'IJK', 'MNO']

My desired final output is something like:

[('A', 'E', 'I', 'M'), ('B', 'F', 'J', 'N'), ('C', 'G', 'K', 'O')]

My desired output is what I am expecting to see after using zip() in some way. My problem is that I cannot find the right way to zip each element of one array together.

Essentially, I am trying to get the columns out of a group of rows.

What I have tried so far:

  1. Splitting the data into a two dimensional list:

    split_data = [list(row) for row in rows]

which gives me:

[['A', 'B', 'C'], ['E', 'F', 'G'], ['I', 'J', 'K'], ['M', 'N', 'O']]
  1. Trying to use zip() on that with something like:

    zip(split_data)

I continue to end up with this:

[(['A', 'B', 'C'],), (['E', 'F', 'G'],), (['I', 'J', 'K'],), (['M', 'N', 'O'],)]

Obviously, it is zipping each element with nothing, causing it to return the original data tupled with a blank. How can I get zip() to consider each element of data or split_data as a list that should be zipped?

What I need is zip(data[0], data[1], data[2], ...)

gliemezis
  • 778
  • 2
  • 6
  • 18

1 Answers1

8

Just unpack the data:

>>> data = ['ABC', 'EFG', 'IJK', 'MNO']
>>> zip(*data)
[('A', 'E', 'I', 'M'), ('B', 'F', 'J', 'N'), ('C', 'G', 'K', 'O')]

As for the explanation, I cannot explain it better and more concise than @Martijn did here:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195