-2

如何从三个列表(年、动物和销售额)中写入文本文件(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
4

3 回答 3

3

这可以处理年数可变的情况。

蟒蛇 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)
于 2013-11-09T06:46:21.123 回答
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    
于 2013-11-09T06:49:02.607 回答
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
于 2013-11-09T06:48:54.403 回答