Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip together each element of one list

Tags:

python

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], ...)

like image 708
gliemezis Avatar asked Apr 02 '16 15:04

gliemezis


Video Answer


1 Answers

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:

  • How to unzip a list of tuples into individual lists?
like image 195
alecxe Avatar answered Sep 20 '22 10:09

alecxe