flyingmouse
flyingmouse

Reputation: 1044

How to use zip and map to write csv file in Python?

I want to combine a data array x, and a label array y, into one csv file. For example:

x = ['first sentence', 'second sentence', 'third sentence']
y = [['1', '0', '1'],['1', '1', '0'],['0', '0', '1']]

The result in the csv file should be (4 column 3 rows):

first sentence,1,0,1
second sentence,1,1,0
third sentence,0,0,1

My code is:

z = map(list, zip(x, (j for j in y)))

But the result is not correct, it is still 2 columns. and I don't know why.

Upvotes: 1

Views: 539

Answers (2)

YCFlame
YCFlame

Reputation: 1289

Because (j for j in y) gives you a tuple (['1','0','1'],['1','1','0'],['0','0','1']), which is somehow the same with the original [['1','0','1'],['1','1','0'],['0','0','1']] to use in zip function(they are both iterators).

I think you may apply list comprehension as follows:

z = [','.join([name] + values) for name, values in zip(x, y)]

which will give you ['first sentence,1,0,1', 'second sentence,1,1,0', 'third sentence,0,0,1']

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149853

You could use a list comprehension to get the list of rows:

>>> x = ['first sentence', 'second sentence', 'third sentence']
>>> y = [['1','0','1'],['1','1','0'],['0','0','1']]
>>> [[a] + b for a, b in zip(x, y)]
[['first sentence', '1', '0', '1'], ['second sentence', '1', '1', '0'], ['third sentence', '0', '0', '1']]

or using map():

>>> list(map(lambda a, b: [a] + b, x, y))
[['first sentence', '1', '0', '1'], ['second sentence', '1', '1', '0'], ['third sentence', '0', '0', '1']]

Upvotes: 1

Related Questions