简体   繁体   中英

More efficient way to convert a nested list to .csv in python

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM