我在Python中有三个列表。我想将这些列表另存为以分号分隔的文本文件(带有标题)。
例如,让我们考虑以下三个列表:
l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
l2 = [1,2,3,4,5]
l3 = [20.0, 25.1, 51.2, 60.2, 75.0]
和标题['Label1', 'Label2', 'Label3']
我希望这些列表以以下形式另存为文本文件中的列:
Label1; Label2; Label3
a1;1;20.0%
a2;2;25.1%
a3;3;51.2%
a4;4;60.2%
a5;5;75.0%
除了以上述格式保存文件外,我还希望在写入最后一列时使用百分比符号。我查看了this帖子,但对于如何实现此功能仍然感到困惑。我正在使用python 2.7。
我将非常感谢您的帮助。
答案 0 :(得分:3)
l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
l2 = [1,2,3,4,5]
l3 = [20.0, 25.1, 51.2, 60.2, 75.0]
header = ['Label1', 'Label2', 'Label3']
import csv
with open('output.csv', 'w') as f:
w = csv.writer(f, delimiter=';')
w.writerow(header)
for row in zip(l1, l2, (str(x)+'%' for x in l3)):
w.writerow(row)
答案 1 :(得分:1)
l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
l2 = [1,2,3,4,5]
l3 = [20.0, 25.1, 51.2, 60.2, 75.0]
answer = ''
for i in range(len(l1)):
value = "{0};{1};{2}%".format(l1[i], l2[i], l3[i])
answer = answer+"\n"+value
header = ['Label1', 'Label2', 'Label3']
title = ';'.join(header)
answer = title + answer
print(answer)
file = open("answer.txt","w")
file.write(answer)
file.close()
答案 2 :(得分:1)
您可以使用zip
转置行,然后使用csv
模块对其进行处理。
>>> import csv
>>> l1 = ['a1', 'a2', 'a3', 'a4', 'a5']
>>> l2 = [1,2,3,4,5]
>>> l3 = [20.0, 25.1, 51.2, 60.2, 75.0]
>>> l3_percent = ['{!r}%'.format(x) for x in l3]
>>> header = ['Label1', 'Label2', 'Label3']
>>> rows = zip(l1, l2, l3_percent)
>>>
>>> with open('out.csv', 'w') as f:
...: writer = csv.writer(f, delimiter=';', quoting=csv.QUOTE_NONE)
...: writer.writerow(header)
...: writer.writerows(rows)
这产生
Label1; Label2; Label3
a1; 1; 20.0%
a2; 2; 25.1%
a3; 3; 51.2%
a4; 4; 60.2%
a5; 5; 75.0%