Using Python to get a CSV output for the following example

无人久伴 提交于 2019-12-12 21:06:37

问题


I'm back again with my ongoing saga of Student-Project Allocation questions. Thanks to Moron (who does not match his namesake) I've got a bit of direction for an evaluation portion of my project.

Going with the idea of the Assignment Problem and Hungarian Algorithm I would like to express my data in the form of a .csv file which would end up looking like this in spreadsheet form. This is based on the structure I saw here.

|          | Project 1 | Project 2 | Project 3 |
|----------|-----------|-----------|-----------|
|Student1  |           |     2     |     1     |
|----------|-----------|-----------|-----------|
|Student2  |     1     |     2     |     3     |
|----------|-----------|-----------|-----------|
|Student3  |     1     |     3     |     2     |
|----------|-----------|-----------|-----------|

To make it less cryptic: the rows are the Students/Agents and the columns represent Projects/Task. Obviously ONE project can be assigned to ONE student. That, in short, is what my project is about. The fields represent the preference weights the students have placed upon the projects (ranging from 1 to 10). If blank, that student does not want that project and there's no chance of him/her being assigned such.

Anyway, my data is stored within dictionaries. Specifically the students and projects dictionaries such that:

students[student_id] = Student(student_id, student_name, alloc_proj, alloc_proj_rank, preferences) 
    where preferences is in the form of a dictionary such that
        preferences[rank] = {project_id}

and

projects[project_id] = Project(project_id, project_name)

I'm aware that sorted(students.keys()) will give me a sorted list of all the student IDs which will populate the row labels and sorted(projects.keys()) will give me the list I need to populate the column labels. Thus for each student, I'd go into their preferences dictionary and match the applicable projects to ranks. I can do that much.

Where I'm failing is understanding how to create a .csv file. Any help, pointers or good tutorials will be highly appreciated.


回答1:


Check out the csv module. Basically, you just need to get your data into some kind of sequence (list, tuple, etc.), and then you can just do csv.writerow()

import csv
cot=csv.writer(open('file.csv','wb'))

tmp=[['','Project 1','Project 2','Project 3'],
     ['Student1','','2','1'],
     ['Student2','1','2','3'],
     ['Student3','1','3','2']]
for t in tmp:
    cot.writerow(t)



回答2:


The csv module was made for just that.



来源:https://stackoverflow.com/questions/2937586/using-python-to-get-a-csv-output-for-the-following-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!