简体   繁体   中英

How do I write a list to a csv and make each element in the list be its own column?

Say I have a list in python like so:

my_list = ['35.32', '23.12', '34.34']

I want to be able to do something like so:

writerposts.writerow(["cat", "meow", my_list])

The above puts all the values in my_list into a single column though with the square brackets representing the list still there. So the csv looks like:

cat meow ['35.32', '23.12', '34.34']

where the parts in between the square brackets are all in one column

but i want it to look like with the floating numbers all in their own columns:

cat meow 35.32 23.12 34.34

This seems so simple but i can't find anyone online explaining how to do this - thoughts??

If you are on Python 3 you can use sequence unpacking:

writerposts.writerow(["cat", "meow", *my_list])

Or a more backwards compatible solution:

writerposts.writerow(["cat", "meow"] + my_list)

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