我有一个 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
等等。
任何人都可以帮助我如何做到这一点吗?
我有一个 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
等等。
任何人都可以帮助我如何做到这一点吗?
使用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
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)
如果您有所有这些列表的列表,例如
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')
>>> 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