-2

3つのリスト(年、動物、売上)からテキストファイル(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

これは、可変の年数がある場合を処理します。

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)
于 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 に答える