简体   繁体   English

如何将列表写入csv,并使列表中的每个元素成为其自己的列?

[英]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: 假设我在python中有一个列表,如下所示:

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. 上面的代码将my_list中的所有值放在一列中,尽管方括号仍然表示列表。 So the csv looks like: 因此,csv看起来像:

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: 如果您使用的是Python 3,则可以使用序列解压缩:

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

Or a more backwards compatible solution: 或更向后兼容的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python 2.7.2中获取一串数字并使每个数字成为列表中自己的元素? - How do I take a string of numbers in Python 2.7.2 and make each number its own element in a list? 导入 CSV 文件并使每列成为自己的列表 - Import CSV file and make each column its own list 将列表导出为CSV或XML,并将每个子列表导出到自己的列中-重新发布 - Exporting a list to a CSV or XML and each sublist in its own column - Repost 如何使输出的最后一列仅包含列表的每个元素而不是整个列表? - How do I make the last column of my output include only each element of the list instead of the whole list? 将每个列表作为列编写csv - Write csv with each list as column 将每一列作为自己的列表 - Taking each column as its own list 如何将列表传递给 python 中的 CSV 编写器并使其在单个单元格中写入每个元素 - How to pass a list to a CSV writer in python and make it write each element in individual cells 如何在 python 中获得 function 以在 2 个列表(每个列表都有自己的 x、y)之间进行插值? - How do I get a function in python to interpolate between 2 list (each with its own x, y)? 如何将字符串列表写入 CSV 文件,列表中的每一项都在一个新行中? - How do I write a list of strings to a CSV file, with each item of the list on a new row? 如何将列表的每个元素写入csv文件的单独字段中? - How to write each element of a list into a seperate field in a csv file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM