Python:将嵌套列表对象写入csv文件 [英] Python: Write nested list objects to csv file

查看:521
本文介绍了Python:将嵌套列表对象写入csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列表列表中的数据写入csv文件.这是我所拥有的简化版本

I'm trying to write data from a list of lists to a csv file. This is a simplified version of what I have

class Point(object): 
    def __init__(self, weight, height):
        self.weight = weight
        self.height = height
    def get_BMI(self):
        return (self.weight * self.height) / 42  # this is not how you calculate BMI but let's say

myList = [[Point(30, 183)],[Point(63, 153)]]

由于数据的设置方式,我将点存储在嵌套循环中.如果要访问第一个点对象的BMI,请输入

Because of the way the data is set up, I store the points in a nested loop. If I wanted to access the first point object’s BMI, I would type

myList[0][0].get_BMI()

我想将每个点的BMI写入CSV(以逗号分隔).我该怎么办?

I want to write each point's BMI to a CSV (delimited by a comma). How do I do that?

这是我的想法,但这并不完全直接:

Here's how I thought but it isn't exactly straight forward:

import csv
with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(myList)

它不会返回任何错误,但实际上也不会创建CSV文件.我也想将myList[i][j].get_BMI()中的值写入文件.权限没有问题,因为我将Spyder(python IDE)用作根用户.现在,我只是通过Spyder控制台运行脚本,但是它仍然可以正常工作并输出CSV文件.

It doesn't return any error however it doesn't actually create the CSV file either. Also I want to write the values in myList[i][j].get_BMI() to file. I don't have a problem with permissions because I use Spyder (python IDE) as root. Right now I'm just running the script through the Spyder console but it should still work and output the CSV file.

推荐答案

writerows 需要一个字符串或数字列表.您应该首先创建一个包含BMI值的列表,以便它们可以写入您的csv文件:

import csv
BMIs = [[point.get_BMI() for point in points] for points in myList]
with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(BMIs)

这篇关于Python:将嵌套列表对象写入csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆