如何在Python中将两个元素写入一行

fly*_*use 1 python

目标很简单,假设我有一个数据数组x和一个标签数组y,它们是两个独立的文件.例如:

x= [['first sentence'],['second sentence'],['third sentence']]
y= [1,0,1]
Run Code Online (Sandbox Code Playgroud)

我想得到一个组合的3*2 csv文件:

first sentence, 1
second sentence, 0
third sentence, 1
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法来完成这项工作?我的代码是导入csv包并使用双循环,但我相信存在一种更简单的方法.

Pau*_*ney 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))
Run Code Online (Sandbox Code Playgroud)

输出:

first sentence, 1
second sentence, 0
third sentence, 1
Run Code Online (Sandbox Code Playgroud)


Tig*_*kT3 5

使用zip().

x = [['first sentence'],['second sentence'],['third sentence']]
y = [1,0,1]
...
for a,b in zip(x,y):
    writer.writerow(a+[b])
Run Code Online (Sandbox Code Playgroud)