[英]What is a better way to store a list of properties against one item in Python?
I am generating a list of computers attached to a server. 我正在生成一个连接到服务器的计算机列表。 For each computer I gather a list of properties.
对于每台计算机,我收集了一个属性列表。 I am new to Python and programming and am finding my solution rather clunky.
我是Python和编程的新手,我发现我的解决方案相当笨重。
I was doing this with lists. 我是用列表做的。 I have a master list:
computer_list
and each computer is another list, with attributes such as status, date, profile, etc. 我有一个主列表:
computer_list
,每台计算机是另一个列表,具有状态,日期,配置文件等属性。
computer_list = [cname1, cname2, cname3]
cname1 = ['online', '1/1/2012', 'desktop']
The downsides of this method are becoming obvious the more I work and change this program. 这种方法的缺点越来越明显,我工作和改变这个程序。 I'm hoping for something more intuitive.
我希望有更直观的东西。 I looked into dictionaries, but that solution seems almost as convoluted as mine.
我查看了词典,但这个解决方案看起来和我的一样复杂。 The list within a list is workable but not readable once I start iterating and assigning.
一旦开始迭代和分配,列表中的列表是可行的但不可读。 I am sure there is a better way.
我相信有更好的方法。
Making a Computer
object which stores fields describing the computer's properties and state is a viable approach. 制作一个存储描述计算机属性和状态的字段的
Computer
对象是一种可行的方法。
You should read more on classes, but something like below should suit your needs: 您应该阅读更多关于课程的内容,但下面的内容应该符合您的需求:
class Computer(object):
def __init__(self, status, date, name):
self.status = status
self.date = date
self.hostname = name
# (useful methods go here)
Perhaps you'd initialize Computer
objects and store them in a list like so: 也许您初始化
Computer
对象并将它们存储在如下列表中:
comp1 = Computer("online", "1/1/2012", "desktop")
comp2 = Computer("offline", "10/13/2012", "laptop")
computers = [comp1, comp2]
Make each computer an object: 使每台计算机成为一个对象
class Computer(object):
def __init__(self, name, status, date, kind):
self.name = name
self.status = status
self.date = date
self.kind = kind
@classmethod # convenience method for not repeating the name
def new_to_dict(cls, name, status, date, kind, dictionary):
dictionary[name] = cls(name, status, date, kind)
Then store these in a dictionary or list. 然后将它们存储在字典或列表中。
computer_list = []
computer_list.append(Computer("rainier", "online", "1/1/2012", "desktop"))
computer_dict = {}
Computer.new_to_dict("baker", "online", "1/1/2012", "laptop", computer_dict)
Now when you iterate over them, it's straightforward: 现在当你迭代它们时,它很简单:
for comp in computer_list:
print comp.name, comp.status, comp.date, comp.kind
You can also define __str__()
on the class to define how they are displayed, and so on. 您还可以在类上定义
__str__()
以定义它们的显示方式,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.