Python: Write nested list objects to csv file

2024/10/14 0:24:08

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 = weightself.height = heightdef get_BMI(self):return (self.weight * self.height) / 42  # this is not how you calculate BMI but let's saymyList = [[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

myList[0][0].get_BMI()

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)

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.

Answer

writerows expects a list of list of strings or numbers. You should start by creating a list with the BMI values so that they can get written into your csv file:

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)
https://en.xdnf.cn/q/118019.html

Related Q&A

Entire module is not detected by __init__.py

I have a relatively small python program which is setup like thisRoot--Network--DTOLots of py files which contain classes.Other py files in the projectBoth in the Network and the DTO folder there is an…

Python output to terminal during ssh login

I have been looking everywhere for this and have not found a solution. I am using python 2.5.1 on an Apple iPod and I am trying to connect to a host with SSH. First I start off with import os. Next I o…

Unable to find SIFT or xfeatures2d in OpenCV Python [duplicate]

This question already has answers here:PyCharm: Installation of non-free OpenCV modules for operations like SIFT, SURF(2 answers)Closed 6 years ago.I recently switch back to python for facial detection…

Django paginate for django 2

I need to use pagination to a Django list but I couldnt find any help online,, only old docs from Django version 1.3 here are my files : views.pydef home(request):all_dress = Item.objects.all().filter(…

AttributeError Button object has no attribute scrlFBtn

from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.core.window import Window from kivy.uix.scrollview import ScrollView from kivy.effects.scrol…

How to set interpreter of WinPython as the vim default python interpreter?

I use a Python distribution named WinPython. Now I want my vim to use the python interpreter in WinPython as its default interpreter. I tried add the F:\WinPython\python-2.7.3.amd64 into my windows env…

how to deal with Python BaseHTTPServer killed,but the port is still be occupied?

I use python BaseHTTPServer,it can handle do_GET,do_POST methods,in do_POST method,i execute linux shell using os.system,when i kill the python script,but the listening port still occupied,so i cant ru…

Circular imports and class fields in python3

Okay, I do understand that this topic is old as hell, but I couldnt find an answer to the particular question that I am asking.Lets say that we have a very simple structure: two files, a.py and b.py, t…

Bad HTTP response returned from the server. Code 500

I have a problem to use pywinrm on linux, to get a PowerShell Session. I read several posts and questions on sites about that. But any that can solve my question. The error is in the Kerberos autenti…

Iterate one list of synsets over another

I have two sets of wordnet synsets (contained in two separate list objects, s1 and s2), from which I want to find the maximum path similarity score for each synset in s1 onto s2 with the length of outp…