简体   繁体   English

Python:将嵌套列表对象写入 csv 文件

[英]Python: Write nested list objects to csv file

I'm trying to write data from a list of lists to a csv file.我正在尝试将列表列表中的数据写入 csv 文件。 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)]]

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如果我想访问第一个点对象的 BMI,我会输入

myList[0][0].get_BMI()

I want to write each point's BMI to a CSV (delimited by a comma).我想将每个点的 BMI 写入 CSV(以逗号分隔)。 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)

It doesn't return any error however it doesn't actually create the CSV file either.它不会返回任何错误,但实际上也不会创建 CSV 文件。 Also I want to write the values in myList[i][j].get_BMI() to file.另外我想将myList[i][j].get_BMI()的值写入文件。 I don't have a problem with permissions because I use Spyder (python IDE) as root.我没有权限问题,因为我使用 Spyder(python IDE)作为 root。 Right now I'm just running the script through the Spyder console but it should still work and output the CSV file.现在我只是通过 Spyder 控制台运行脚本,但它应该仍然可以工作并输出 CSV 文件。

writerows expects a list of list of strings or numbers. writerows需要一个字符串或数字列表。 You should start by creating a list with the BMI values so that they can get written into your csv file:您应该首先创建一个包含 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)

There are three issues:存在三个问题:

  1. The nested lists must be flattened.嵌套列表必须展平。 To accomplish this, use itertools.chain.from_iterable .为此,请使用itertools.chain.from_iterable

  2. The row data for the CSV must be customized.必须自定义 CSV 的行数据。 To accomplish this, use list comprehensions .要做到这一点,请使用列表理解

  3. output.csv is not being created.未创建 output.csv。 I suspect that the output.csv is being created but being placed in an unexpected location.我怀疑正在创建 output.csv 但被放置在意外的位置。 You could try hardcoding a full path for testing to see if this is the case.您可以尝试对完整路径进行硬编码以进行测试,以查看是否是这种情况。

Here is code that demonstrates #1 and #2:这是演示 #1 和 #2 的代码:

import csv
from itertools import chain

with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    flattenedList = chain.from_iterable(myList)

    writer.writerows((pt.weight, pt.height, pt.get_BMI()) for pt in flattenedList)

You can do this with writerows , as it expects a list of rows - each row should be formatted as per the dialect parameter to csv.writer , which can be ignored in this case without fear of any backfiring.您可以使用writerows来做到这writerows ,因为它需要一个rows列表 - 每row应该按照csv.writerdialect参数进行csv.writer ,在这种情况下可以忽略它而不必担心任何适得其反。

So writerows can take a structure that looks like myList .所以writerows可以采用类似于myList的结构。 The problem is that you need to access all the points and grab their BMIs (this can be done in a list comprehension)问题是您需要访问所有点并获取它们的 BMI(这可以在列表理解中完成)

To illustrate how writerows can be used (and to add a number to each point, so that all your rows don't have just one entry (which would be frustrating), I added the call to enumerate.为了说明如何使用 writerows(并为每个点添加一个数字,以便您的所有行都不会只有一个条目(这会令人沮丧),我添加了对 enumerate 的调用。

Therefore, you no longer need complex loops or any such.因此,您不再需要复杂的循环或任何此类。 Enjoy:享受:

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

with open('output.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    writer.writerows(enumerate(p.get_BMI() for p in itertools.chain.from_iterable(myList)))
myList = [[Point(30, 183)],[Point(63, 153)]]

with open('output.csv', 'w') as outfile:
    writer = csv.writer(outfile,delimiter=',')
    for i in myList:
         writer.writerow([i]) 

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

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