写一个列到列

时间:2012-09-06 04:25:37

标签: python

我有一个Python数据列表:

[1,2,3,4,5]

我希望通过以下方式将此数据作为列读取到文件中:

1
2
3
4
5

然后我希望将我的下一个列表([6,7,8,9,10])添加到其中(带标签):

1 6  
2 7  
3 8  
4 9  
5 10  

等等。

有人可以帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:6)

使用zip()

with open('data.txt','w') as f:
    lis=[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
    for x in zip(*lis):
        f.write("{0}\t{1}\t{2}\n".format(*x))

<强>输出:

1   6   11

2   7   12

3   8   13

4   9   14

5   10  15

答案 1 :(得分:4)

col1,col2 = [1,2,3,4,5],[6,7,8,9,10]

>>> output = '\n'.join('\t'.join(map(str,row)) for row in zip(col1,col2))
>>> print(output)
1       6
2       7
3       8
4       9
5       10

要写入文件:

with open('output.txt', 'w') as f:
    f.write(output)

答案 2 :(得分:3)

如果您有所有这些列表的列表,例如

data = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

您可以使用zip(*data)转置它来获取

[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]

然后用

之类的东西写出来
with open('filename', 'w') as f:
    for row in zip(*data):
        f.write('\t'.join(row)+'\n')

答案 3 :(得分:2)

>>> from itertools import izip
>>> with open('in.txt') as f:
...    input = [s.strip() for s in f.readlines()]
...
>>> input
['1', '2', '3', '4', '5']
>>> combine = ['6','7','8','9','10']
>>> with open('out.txt','w') as f:
...     for x in izip(input,combine):
...         f.write("{0}\t{1}\n".format(x[0],x[1]))
...
>>> quit()
burhan@sandbox:~$ cat out.txt
1       6
2       7
3       8
4       9
5       10