下面有一个类似于Python_List
的嵌套列表,我想做一个如下所示的.csv
:
Python_List|-> .csv
[['2','4'],| 2,4
['6','7'],| 6,7
['5','9'],| 5,9
['4','7']]| 4,7
到目前为止,我正在使用以下代码:
Python_List=[['2','4'], ['6','7'], ['5','9'], ['4','7']]
with open('test.csv','w') as f:
for i in range(0,len(Python_List)):
f.write('%s,%s\n' %(Python_List[i][0],Python_List[i][1]))
有没有其他更有效的选择?
发布于 2014-01-03 10:30:52
考虑使用csv模块的编写者方法。
它可能不是更有效率,但它将更容易理解。
例如
import csv
with open('test.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerows(Python_List)
发布于 2014-01-03 10:33:39
>>> i = [['2','4'], ['6','7'], ['5','9'], ['4','7']]
>>> with open('test.csv','w') as f:
... writer = csv.writer(f)
... writer.writerows(i)
...
>>> quit()
$ cat test.csv
2,4
6,7
5,9
4,7
发布于 2014-01-03 10:32:51
您可以使用csv模块及其writer
方法,如下所示
pyList = [['2','4'], ['6','7'], ['5','9'], ['4','7']]
import csv
with open('Output.txt', 'wb') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
map(csvwriter.writerow, pyList)
https://stackoverflow.com/questions/20901531
复制相似问题