将多个列表写入单个列

时间:2013-07-11 18:43:32

标签: python list csv

我想读一个像这样的2列文件:

1 3
4 7
2 8

并获取一个像这样的单个列文件:

3
7
7
7
7
8
8

这是我的代码:

import csv
array1 = []
array2 = []
with open('test.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        array1.append(row[0])
        array2.append(row[1])
range1 = len(array1)
array1 = [int(x) for x in array1]
array2 = [int(x) for x in array2]

outfile = open('drp', 'wb')
writer=csv.writer(outfile)

for s in range(0, range1, 1):
            res = [array2[s]] * array1[s]
            print res
            writer.writerow([res])
outfile.close()  

除了最后的写作步骤之外,它似乎正在起作用。我在输出文件中得到的是:

[3]  
"[7, 7, 7, 7]"  
"[8, 8]"

显然我没有正确使用csv编写器。有什么建议?感谢。

4 个答案:

答案 0 :(得分:1)

你正在使这个简单问题复杂化:

import csv
with open('test.txt') as f, open('out.csv','w') as f2:
    writer = csv.writer(f2, delimiter = '\n')
    for line in f:
        x, y = line.split() 
        writer.writerow([y]*int(x))

输出

>>> cat out.csv
3
7
7
7
7
8
8

答案 1 :(得分:0)

您是否有任何特殊原因以二进制模式或使用csv读取文本文件?

with open('test.txt', 'r') as f, open('drp','w') as ff::
     for l in f:
         a,b=l.split(' ')
         for i in range(int(a)):
             ff.write(b+'\n')

答案 2 :(得分:0)

这应该这样做

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        mult, val = line.strip().split()
        outfile.write('\n'.join([val for _ in xrange(int(mult))]))
        outfile.write('\n')

答案 3 :(得分:0)

另一个选择

from itertools import chain
with open('test.txt') as f:
    z = (line.split() for line in f)
    print '\n'.join(chain.from_iterable(int(x)*[y] for (x, y) in z))