【问题标题】:Turning list of lists into objects将列表列表转换为对象
【发布时间】:2013-12-02 16:42:59
【问题描述】:

我目前有一个列表列表,其中每个列表都包含相同类型的信息,例如:

[['Planet Name', 16, 19, 27, 11], ['Planet Name 2', 12, 22, 11, 42], ....]

我想使用一个类将其制成具有相同信息的对象列表,其中索引 0 是 self.name,索引 1 是 self.distance 等等,每个单独的列表。

我知道我需要使用某种 for 循环,但不知道如何去做。

非常感谢一些帮助,我正在尝试学习 Python 和当前的课程!

【问题讨论】:

  • 请详细说明:“其中index 0是self.name,index 1是self.distance等等”你要的字段名是什么?

标签: python list class


【解决方案1】:

您可以像这样使用namedtuple 来动态创建一个对象,其中包含字段名称列表。 *item在这段代码中被调用,unpacking of arguments list

from collections import namedtuple
Planet = namedtuple("Planet", ["name", "distance", "a", "b", "c"])

data = [['Planet Name', 16, 19, 27, 11],['Planet Name 2', 12, 22, 11, 42]] 
for item in data:
    planet = Planet(*item)
    print planet.name, planet.distance, planet

输出

Planet Name 16 Planet(name='Planet Name', distance=16, a=19, b=27, c=11)
Planet Name 2 12 Planet(name='Planet Name 2', distance=12, a=22, b=11, c=42)

注意: namedtupletuple 的子类。因此,使用namedtuple 创建的所有对象都是不可变的。也就是说,一旦创建了对象,成员变量中的数据就不能再改变了。

【讨论】:

  • 我喜欢这个答案,但它应该附带免责声明,namedtuples 是不可变的
【解决方案2】:

嗯...要创建一个您想要的课程,您可以执行以下操作:

class Planet(object):
    def __init__(self, *args, **kwargs):
        self.name = args[0]
        self.distance = args[1]
        # ... etc ...

或者是这样的:

class Planet(object):
    def __init__(self, name, distance, ...):
        self.name = name
        self.distance = distance
        # ... etc ...

然后你这样称呼它:

p = Planet(*['Planet Name', 16, 19, 27, 11])

在一个循环中:

l = [['Planet Name', 16, 19, 27, 11], ['Planet Name 2', 12, 22, 11, 42], ....]
planets = [Planet(*data) for data in l]

【讨论】:

    【解决方案3】:

    我很困惑。你创建了 Planet 构造函数了吗? 代码类似于:

    class Planet(object):
        def __init__(self, ....):
    
    ....
    
    planets = [['Planet Name', 16, 19, 27, 11]['Planet Name 2', 12, 22, 11, 42]....] 
    planet_list = [Planet(*p) for p in planets]
    

    【讨论】:

      【解决方案4】:

      如果您不希望有一个知道列表细节的构造函数 (__init__),您可以这样做

      lists = [['Planet Name', 16, 19, 27, 11], ['Planet Name 2', 12, 22, 11, 42]]
      
      class Planet(object):
          pass
      
      for l in lists:
          planet = Planet()
          setattr(planet, 'name', l[0])
          setattr(planet, 'distance', l[1])
          setattr(planet, 'size', l[2])
          print planet.name, planet.distance, planet.size
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 2021-06-28
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多