在python中将嵌套列表转换为.csv的更有效方法

时间:2014-01-03 10:29:31

标签: python csv

我有一个如下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]))

有没有更有效的替代方案?

3 个答案:

答案 0 :(得分:4)

考虑使用csv模块的writer方法。

它可能效率不高,但更容易理解。

例如

import csv
with open('test.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',')
    csvwriter.writerows(Python_List)

答案 1 :(得分:2)

>>> 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

答案 2 :(得分:1)

您可以使用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)