首页 \ 问答 \ 从列表中创建一个__init__类(make a class __init__ from a list)

从列表中创建一个__init__类(make a class __init__ from a list)

我有这样的东西,硬编码:

class csv_row:
  def __init__(self, name, time, more_stuff):
    self.name = name
    self.time = time
    self.more_stuff = more_stuff

这个类是csv行的表示。 我想要做的是使它更通用,并抓住csv文件的头部并使用它以与此列表相同的方式初始化它。 像这样的东西:

class csv_row:
  def __init__(self, list_of_attrs):
    for column in list_of_attrs:
      # initialize a self.variable with the same name as the column 

例如,csv的标题是[name, time, something] 。 传递的__init__将初始化为:

self.name = name
self.time = time
self.something = something

如何才能做到这一点?


I have something like this, hardcoded:

class csv_row:
  def __init__(self, name, time, more_stuff):
    self.name = name
    self.time = time
    self.more_stuff = more_stuff

this class is the representation of a csv row. What I want to do is make this more generic, and grab the head of the csv file and use it to initialize it in the same way as this list. Something like so:

class csv_row:
  def __init__(self, list_of_attrs):
    for column in list_of_attrs:
      # initialize a self.variable with the same name as the column 

for example, the header for a csv is [name, time, something]. The __init__, when passed that, will initialize with:

self.name = name
self.time = time
self.something = something

How can this be done?


原文:https://stackoverflow.com/questions/23275587
更新时间:2019-12-03 08:14

最满意答案

已经有几个设施来处理这样的事情。 没有必要重新发明轮子:

namedtuple

from collections import namedtuple
headers = ["one", "two", "three"]

CustomRow = namedtuple("CustomRow", headers)

a_row = CustomRow(1, 2, 3)
a_row.one == 1 # True
a_row.two == 2 # True
a_row.three == 3 # True

csv.DictWritercsv.DictReader

import csv

with open("my_file.csv", "rb") as f:
    reader = csv.DictReader(f, ["one", "two", "three"])
    for line in reader:
        print line["one"] # prints the 1st column
        print line["two"] # etc.
        print line["three"] # etc., etc.

There already exist several facilities for dealing with something like this. There is no need to reinvent the wheel:

namedtuple

from collections import namedtuple
headers = ["one", "two", "three"]

CustomRow = namedtuple("CustomRow", headers)

a_row = CustomRow(1, 2, 3)
a_row.one == 1 # True
a_row.two == 2 # True
a_row.three == 3 # True

csv.DictWriter and csv.DictReader

import csv

with open("my_file.csv", "rb") as f:
    reader = csv.DictReader(f, ["one", "two", "three"])
    for line in reader:
        print line["one"] # prints the 1st column
        print line["two"] # etc.
        print line["three"] # etc., etc.
2014-04-24

相关问答

更多

将Vector转换为QJsonArray的最快方法?(Fastest way to convert Vector to QJsonArray?)

恐怕没有比你设计的更快的方法了。 QJsonArray由QJsonValue值组成,可以封装不同类型的本机值: Null , Bool , Double , String ,..., Undefined 。 但是std::vector由一个唯一类型的值组成。 因此,矢量的每个值都应单独转换为QJsonValue ,并且没有像memcopy那样更快的方法。 无论如何,您可以缩短您的功能。 QJsonArray toJson(const std::vector<unsigned short>& my

使用nodejs将SQL推文发送到SQL表中(Get tweet JSON into SQL table with nodejs)

我最终转向使用MongoDB,它与NodeJS非常配合,我真的非常喜欢它。 I eventually moved over to using MongoDB, it works really well with NodeJS and I'm really enjoying it.

如何按“日期”字段排列(dplyr)数据框?(How to arrange (dplyr) a data frame by “date” field?)

我们可以使用backquotes来指定具有前导/滞后空格的列名 df %>% arrange(` date `) 或者更好的方法是通过删除空格( trimws )来rename列,然后使用OP的代码中的trimws 。 df %>% rename_all(trimws) %>% arrange(date) 注意:最好不要在列名中包含空格,无论是前导/滞后还是分隔单词。 通常,如果列名中有多个单词,请使用下划线( _ )连接它。 如果列名没有任何空格('df1'), group_

无法正常启动Mariadb?(Can't start Mariadb properly?)

我在几天内遇到类似的问题。 我的问题通过将内存从512MB增加到至少1GB来解决(尽管您的问题似乎与内存无关)。 我建议检查是否启用了SELinux 。 默认情况下,它是在新的CentOS 7服务器上 。 设置 SELINUX=disabled 在这个文件中 cat /etc/selinux/config 解决了我的问题。 希望能帮助到你。 I struggle with a similar issue for a few days. My issue was solved by incre

(Pandas)组合两个数据帧的不同方式((Pandas) Different way of combining two dataframes)

对我来说工作np.union1d : import numpy as np idx = np.union1d(index.indexer_between_time('7:00','9:00'), index.indexer_between_time('12:00','14:00')) comb_data = df.iloc[idx] print (comb_data) date value 7 2000-01-

如何在c函数中返回列表?(How to return lists in c functions?)

您的插入函数以相反的顺序插入。 那是因为你将root分配给l->next而l分配给root 。 当用户尝试结束插入过程时,数字0也包含在列表中。 在main() ,你似乎没有将函数lins()的返回值赋给变量,如果你传递l声明为List l = NULL; 到函数lins() ,然后将使用它的副本,因此原始变量不会被更改。 你真正需要的是: #include <stdio.h> #include <stdlib.h> typedef struct list_element { int

生产中的Outlook 2013应用程序部署(Outlook 2013 app deployment in production)

不,您无法使用MSI部署Office应用程序。 No, you can't deploy Office Apps using MSI.

运行时计算(Run-Time Calculation)

听起来你真的只想传递x2作为参数。 然后,当您知道x2是什么时,您可以调用该函数。 Random random = new Random(); public int SetPointLocation(int x2) { int x1 = x2 - 20; int x3 = x2 + 20; int y2 = Convert.ToInt32((picBox.Name).Remove(0, 10)); int y1 = y2 - 1; int y3 = y2

相关文章

更多

最新问答

更多
  • 读取UITextfields的值时出错(Error in reading values of UITextfields)
  • 将javascript变量分配给java变量(Assigning javascript variable to java variable)
  • ActiveRecord_Associations_CollectionProxy的未定义方法(Undefined method for ActiveRecord_Associations_CollectionProxy)
  • 返回两个字符串作为方法签名(Return two strings as method signature)
  • 在弹簧启动应用程序中自动连接对象(Auto wiring an object in spring boot application)
  • Log4j2 - 当前日期文件追加不起作用(Log4j2 - current date file append not working)
  • 如果已经使用计时器运行,如何解决不受欢迎的webrequest调用?(How to solve undesirable webrequest call if it is already running with timer?)
  • 释放全局变量(Freeing global variable)
  • 如何在标头中添加单独的列以便在jqgrid中进行垂直滚动(How to add separate column in header for vertical scrolling in jqgrid)
  • Javascript / jQuery切换边栏[关闭](Javascript/jQuery Toggling Sidebar [closed])
  • 套接字客户端:没有得到DataInputStream.readUTF()的完整响应(Socket client: don't get the full response with DataInputStream.readUTF())
  • 一个月的数字表示,带或不带前导零(Numeric representation of a month, with or without leading zeros)
  • SAS proc freq用于变量的不同值(SAS proc freq for distinct value of a variable)
  • 将pkg.sub导入为other.sub(importing pkg.sub as other.sub)
  • PaperJs错误并不明显(PaperJs errors are not understable)
  • 访问正文中脚本之外的javascript var(accessing a javascript var outside of script in the body)
  • 使用PowerShell查询单个注册表子项?(Query a single registry subkey using PowerShell?)
  • 可以省去do-while循环中的“do”吗?(Can leaving out the “do” in a do-while loop still work?)
  • Firestore规则:数据为数字时条件检查失败(Firestore rules: condition check fails when data is number)
  • Python:为什么在迭代时会忽略序列的__len __()?(Python: Why is the __len__() of a sequence ignored when iterating?)
  • PlayN中没有发现OpenGL上下文错误(No OpenGL context found error in PlayN)
  • 如何在AWS CodeCommit存储库中创建文件夹?(How to create folder in AWS CodeCommit repository?)
  • awk:将结果发送到使用bash变量命名的文件(awk: send results to file named using bash variable)
  • 卸载视图时防止丢失状态(Prevent loss of state when unmounting view)
  • Android EditText字段在模拟器上运行正常,但不适用于设备(Android EditText field works fine on emulator, but not device)
  • AngularJS在条件有效的ng-repeat中禁用未选中的复选框(AngularJS Disable unchecked checkbox in ng-repeat with condition)
  • codeigniter加载一个没有任何html标题的视图进行打印(codeigniter load a view without any html header for printing)
  • Liferay porlet的动作网址中的例外情况(Exception in the action url of liferay porlet)
  • 条目(XAML表单)对象引用仅与UWP App一起使用(Entry (XAML Form) object reference null only with UWP App)
  • Spring项目中的额外Gradle任务(Extra Gradle tasks in Spring project)