如何从三个列表(年份,动物和销售)中编写文本文件(outfile.txt)?
years=['2009','2010']
animals=['horse','cat','dog','cow','pig']
sales=[[2,300,700,50,45],[4,9,55,69,88]]
with open ('outfile.txt','w' as outfile):
outfile.write(???
outfile.txt应如下所示:
animals years_2009 years_2010
horse 2 4
cat 300 9
dog 700 55
cow 50 69
pig 45 88
答案 0 :(得分:3)
处理存在可变年数的情况。
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)
答案 1 :(得分:2)
我会将销售数据列表拆分,然后只是压缩值:
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
答案 2 :(得分:1)
years = ['2009', '2010']
animals = ['horse', 'cat', 'dog', 'cow', 'pig']
sales = [[2, 300, 700, 50, 45], [4, 9, 55, 69, 88]]
with open('out_file.txt', 'w') as fp:
fp.write("""animals years_{0} years_{1}""".format(years[0], years[1]))
for i, _ in enumerate(animals):
fp.write(animals[i], sales[0][i], sales[1][i])
输出
animals years_2009 years_2010
horse 2 4
cat 300 9
dog 700 55
cow 50 69
pig 45 88