如何使用zip和map在Python中编写csv文件?

时间:2016-01-11 08:00:09

标签: python csv dictionary zip

我想将数据数组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列。而且我不知道为什么。

2 个答案:

答案 0 :(得分:1)

您可以使用列表推导来获取行列表:

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

答案 1 :(得分:0)

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

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

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