More efficient way to convert a nested list to .cs

2020-03-31 08:15发布

I've a nested list like Python_List below and I want to make a .csv like below:

    Python_List|->  .csv
    [['2','4'],|     2,4   
     ['6','7'],|     6,7
     ['5','9'],|     5,9
     ['4','7']]|     4,7

So far I'm using this code:

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

Are there any alternatives more efficient?

标签: python csv
3条回答
该账号已被封号
2楼-- · 2020-03-31 08:29

You can csv module and its writer method, like this

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)
查看更多
一纸荒年 Trace。
3楼-- · 2020-03-31 08:42

Consider using the writer method of the csv module.

It may not be more efficient but it will be easier to understand.

For Example

import csv
with open('test.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',')
    csvwriter.writerows(Python_List)
查看更多
▲ chillily
4楼-- · 2020-03-31 08:47
>>> 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
查看更多
登录 后发表回答