list1 = [1,2,4,5,7,8,9] corresponds to ID
list2 = [3,2,1,1,1,2,3] corresponds to relevance
我有两个不同的列表,例如list1,list2,其中包含数值。我想写两个带有标题[“ID”,“Relevance”]的csv文件。现在我想在标题“ID”中写入list1的值,在标题“Relevance”中写入list2。我写下面的代码试图写两个列表,但它没有给出所需的输出。
我希望输出采用以下样本格式:
ID Relevance
1 3
3 2
4 2
6 1
7 3
10 1
代码:
with open('results_cosine11.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile)
for value in list1,list2:
wr.writerow([value])
答案 0 :(得分:4)
您正在寻找的是zip()
。这将有效:
with open('results_cosine11.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile)
for value in zip(list1,list2):
wr.writerow(value)
或者,更有效率:
with open('results_cosine11.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile)
wr.writerows(zip(list1,list2))
为了也写出标题:
with open('results_cosine11.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile)
wr.writerow(("ID", "Relevance"))
wr.writerows(zip(list1,list2))
答案 1 :(得分:0)
尝试
a= zip(list1,list2)
for id,relevance in a:
#... do whatever