在python中从多个列表生成单个文件
如何从三个列表(年份、动物和销售额)中编写文本文件(outfile.txt) outfile.txt应该如下所示:在python中从多个列表生成单个文件,python,Python,如何从三个列表(年份、动物和销售额)中编写文本文件(outfile.txt) outfile.txt应该如下所示: animals years_2009 years_2010 horse 2 4 cat 300 9 dog 700 55 cow 50 69 pig 45 88 这将处理年份可变的情况 Python 2.7: import itertools with open('outfile.txt', 'w') as outfile: outfile.write('animals
animals years_2009 years_2010
horse 2 4
cat 300 9
dog 700 55
cow 50 69
pig 45 88
这将处理年份可变的情况 Python 2.7:
import itertools
with open('outfile.txt', 'w') as outfile:
outfile.write('animals ' + ' '.join('years_' + y for y in years) + '\n')
for data in itertools.izip(years, animals, *sales):
outfile.write(' '.join(data)+'\n)
Python 3.*:
with open('outfile.txt', 'w') as outfile:
print('animals', *('years_' + y for y in years), file=outfile)
for data in zip(animals, *sales):
print(*data, file=outfile)
输出
animals years_2009 years_2010
horse 2 4
cat 300 9
dog 700 55
cow 50 69
pig 45 88
我会将销售数据列表拆分,然后快速浏览价值:
s = ['2009', '2010']
animals = ['horse', 'cat', 'dog', 'cow', 'pig']
sales = [[2, 300, 700, 50, 45], [4, 9, 55, 69, 88]]
sales_09, sales_10 = sales
with open("animals.txt", 'w') as w:
w.write("{0:^10}{1:^10}{1:1^0}\n".format("Animal", s[0], s[1]))
for animal, nine, ten in zip(animals, sales_09, sales_10):
w.write("{0:^10}{1:^10}{2:^10}\n".format(animal, nine, ten))
输出文件:
Animal 2009 2010
horse 2 4
cat 300 9
dog 700 55
cow 50 69
pig 45 88
OP想要写入文件。@游戏玩家,检查更新now@aIKid喜欢吗?如果有什么我可以改进的,请说出来。我想没有。结果格式很好。@aIKid,他确实包含了他正在尝试的内容(尽管这显然是问题的不完整解决方案)。
s = ['2009', '2010']
animals = ['horse', 'cat', 'dog', 'cow', 'pig']
sales = [[2, 300, 700, 50, 45], [4, 9, 55, 69, 88]]
sales_09, sales_10 = sales
with open("animals.txt", 'w') as w:
w.write("{0:^10}{1:^10}{1:1^0}\n".format("Animal", s[0], s[1]))
for animal, nine, ten in zip(animals, sales_09, sales_10):
w.write("{0:^10}{1:^10}{2:^10}\n".format(animal, nine, ten))
Animal 2009 2010
horse 2 4
cat 300 9
dog 700 55
cow 50 69
pig 45 88