我是python的新手,我有一点问题,假设我有以下内容
数组:L = [[ 1,2,3,4,5,6,7,8,9,10 ] ,[ 2,5,8,9,6,4,7,3,42,7 ]]
,我想将其写入文本文件格式:
1 <\t> 2
2 <\t> 5
3 <\t> 8
4 <\t> 9
5 <\t> 6
6 <\t> 4
7 <\t> 7
8 <\t> 3
9 <\t> 42
10 <\t> 7
任何人都有快速解决方案吗? 我试过了:
L=[[1,2,3,4,5,6,7,8,9,10],[2,5,8,9,6,4,7,3,42,7]]
thefile=open("testo.txt","w")
thefile.write("%s \t %s \n" %L[1][:] %L[2][:])
我收到此错误:
thefile.write("%s \t %s \n" %L[1][:] %L[2][:])
TypeError: not enough arguments for format string
谢谢!
答案 0 :(得分:0)
你几乎明白了,但是字符串插值%
的语法错误,而使用[:]
将整个内部列表作为字符串打印,你需要使用迭代。尝试:
with open('testo.txt', 'w') as f:
for i in range(len(L[1])):
f.write("%s \t %s \n" % (L[0][i], L[1][i]))
或更pythonic方式:
with open('testo.txt', 'w') as f:
for list_item_1, list_item_2 in zip(*L):
f.write("%s \t %s \n" % (list_item_1, list_item_2))