简体   繁体   English

将列表转换为类字段的pythonic方法

[英]pythonic way to convert lists to class fields

Is there a more pythonic way to distribute the content of multiple lists into fields in multiple structures? 有没有更Python的方式将多个列表的内容分布到多个结构的字段中? Example below using pandas.dataframe 以下使用pandas.dataframe

import pandas

# INPUT
files = ['file1.csv','file2.csv','file3.csv','file4.csv', 'file5.csv']
names = ['Cold', 'Hot','Hotter','Hottest','Hottestest']
lines = ['-','-',':','-',':']
colors = ['b','r','r','y','y']
marker = ['','','','o','']

cases = []
for idx,case in enumerate(files):
  cases.append(pandas.read_csv(fname))
  cases[idx].name   = names[idx]
  cases[idx].color  = colors[idx]
  cases[idx].marker = marker[idx]
  cases[idx].lines  = lines[idx]

EDIT: Using Adrian's answer we can simplify this using assign and **kwargs : 编辑:使用阿德里安的答案,我们可以简化使用assign**kwargs

import pandas

# INPUT
file_map = {
    'file1.csv': {
        'name': 'Cold',
        'lines': '-',
        'colors': 'b',
        'marker': ''
    },
    # ...etc...
}

cases = []
for filename, attrs in file_map.iteritems():
    cases.append(pandas.read_csv(filename).assign(**attrs))

OLD ANSWER: 旧答案:

Seems like a dict of dicts would be better. 看起来像是命令的命令会更好。

import pandas

# INPUT
file_map = {
    'file1.csv': {
        'name': 'Cold',
        'lines': '-',
        'colors': 'b',
        'marker': ''
    },
    # ...etc...
}

cases = []
for filename, attrs in file_map.iteritems():
  case = pandas.read_csv(filename)
  for attr, value in attrs.iteritems():
      setattr(case, attr, value)
  cases.append(case)

You could also potentially make the submaps class or collections.namedtuple instances if you wanted to be more strict about it. 如果您想对submaps类或collections.namedtuple实例进行更严格的规定,则还可以使用它。

Your code seems good enough to me. 您的代码对我来说似乎足够好。 But if you want to avoid those assignments at the bottom, try this: 但是,如果您想避免在底部进行这些分配,请尝试以下操作:

import pandas

# INPUT
files = ['file1.csv','file2.csv','file3.csv','file4.csv', 'file5.csv']
names = ['Cold', 'Hot','Hotter','Hottest','Hottestest']
lines = ['-','-',':','-',':']
colors = ['b','r','r','y','y']
marker = ['','','','o','']

cases = [
    pandas.read_csv(fname)
          .assign(name=names[idx],
                  color=colors[idx],
                  marker=marker[idx],
                  lines=lines[idx])
    for idx,case in enumerate(files)
]

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

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