Anna Jeanine
Anna Jeanine

Reputation: 4125

Python ZIP Function gives unexpected output

I am struggling to get the zip function of Python 2.7 to work to provide the output which I need.

Example of the data which I have:

print(score_data[0:3])
[['0/1:7,3:10:99', '0/0:3:3:99'], ['0/0:12:12:99', '0/1:11,7:18:99'], ['0/1:8,7:15:99', '0/1:14,4:18:99']]

The type of output which I want

[['0/1:7,3:10:99','0/1:8,7:15:99', '0/0:12:12:99'], [ '0/1:11,7:18:99','0/0:3:3:99', '0/1:14,4:18:99']]

The output which I am getting:

print(zip(score_data[0:3]))
[(['0/1:7,3:10:99', '0/0:3:3:99'],), (['0/0:12:12:99', '0/1:11,7:18:99'],), (['0/1:8,7:15:99', '0/1:14,4:18:99'],)]

Upvotes: 1

Views: 98

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

You're wrongly applying zip on one list. zip doesn't complain, but it just adds one tuple dimension to your list, not of much use:

>>> list (zip([1,2,3,4]))
[(1,), (2,), (3,), (4,)]

You need to expand the sublists as positional arguments (using * operator) to pass to zip:

z = [['0/1:7,3:10:99', '0/0:3:3:99'], ['0/0:12:12:99', '0/1:11,7:18:99'], ['0/1:8,7:15:99', '0/1:14,4:18:99']]

print(list(zip(*z)))   # convert to list for python 3 compat.

result:

[('0/1:7,3:10:99', '0/0:12:12:99', '0/1:8,7:15:99'), ('0/0:3:3:99', '0/1:11,7:18:99', '0/1:14,4:18:99')]

note that zip issues tuples by default. To create list types instead:

print([list(x) for x in zip(*z)])

result:

[['0/1:7,3:10:99', '0/0:12:12:99', '0/1:8,7:15:99'], ['0/0:3:3:99', '0/1:11,7:18:99', '0/1:14,4:18:99']]

Upvotes: 6

Related Questions