Python如何使用zip和map写入csv文件?

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

我想将数据数组 x 和标签数组 y 合并到一个 csv 文件中。例如:

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

csv 文件中的结果应该是(4 列 3 行):

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

我的代码是:

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

但是结果不对,还是2列。我不知道为什么。

您可以使用列表理解来获取行列表:

>>> 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']]

或使用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']]

因为(j for j in y)给了你一个元组(['1','0','1'],['1','1','0'],['0','0','1']),它在某种程度上与原始[['1','0','1'],['1','1','0'],['0','0','1']]在zip函数中使用的相同(它们都是迭代器)。

我认为您可以按如下方式应用列表理解:

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

这会给你 ['first sentence,1,0,1', 'second sentence,1,1,0', 'third sentence,0,0,1']