目标非常简单,假设我有一个数据数组x
和一个标签数组y
,它们是两个独立的文件。例如:
x= [['first sentence'],['second sentence'],['third sentence']]
y= [1,0,1]
我希望将3 * 2 csv文件合并为:
first sentence, 1
second sentence, 0
third sentence, 1
有没有简单的方法来完成这项工作?我的代码是导入csv
包并使用双循环,但我确信存在一种更简单的方法。
答案 0 :(得分:6)
使用zip
x= [['first sentence'],['second sentence'],['third sentence']]
y= [1,0,1]
for zx,zy in zip(x, y):
print('{}, {}'.format(zx[0], zy))
输出:
first sentence, 1
second sentence, 0
third sentence, 1
答案 1 :(得分:5)
使用zip()
。
x = [['first sentence'],['second sentence'],['third sentence']]
y = [1,0,1]
...
for a,b in zip(x,y):
writer.writerow(a+[b])
答案 2 :(得分:1)
这样的东西?
x = [['first sentence'],['second sentence'],['third sentence']]
y = [1,0,1]
for i,j in zip(x, y):
writer.writerow([i ,j])
答案 3 :(得分:1)
from cStringIO import StringIO
from csv import writer
x = [['first sentence'],['second sentence'],['third sentence']]
y = [1,0,1]
# only take first argument from the labels, zip them with the data and
# dump them into a file:
f = StringIO() # you might want to use open(…)
writer(f).writerows(zip((z[0] for z in x), y))
f.seek(0) # rewind the buffer
print f.read():
first sentence,1
second sentence,0
third sentence,1
C.f。