查询/检索列表中存储的对象(python 3.3)
为了介绍Python赋值,我创建了类的实例,存储在列表中。我可以根据它们在列表中的位置打印或删除它们,但实际上,我需要能够查询单个属性,比如只过滤出可用的属性,更改它们的可用性,或者显示每个对象的成本。我将附上一些代码:查询/检索列表中存储的对象(python 3.3),python,list,class,object,instance,Python,List,Class,Object,Instance,为了介绍Python赋值,我创建了类的实例,存储在列表中。我可以根据它们在列表中的位置打印或删除它们,但实际上,我需要能够查询单个属性,比如只过滤出可用的属性,更改它们的可用性,或者显示每个对象的成本。我将附上一些代码: class Vehicle(): def __init__(self,plateno,kml,dailycost,weeklycost,weekendcost): #attributes common to all vehicles
class Vehicle():
def __init__(self,plateno,kml,dailycost,weeklycost,weekendcost): #attributes common to all vehicles
self.plateno=plateno
self.kml=kml
self.dailycost=dailycost
self.weeklycost=weeklycost
self.weekendcost=weekendcost
self.avail=True
# methods
def __str__(self):b
return "Vehicle Plate Number: {0}, km/l: {1}, daily: {2},weekly: {3}, weekend: {4}".format(self.plateno, self.kml, self.dailycost, self.weeklycost, self.weekendcost)
def __del__(self):
return "Vehicle deleted: {0}".format(self.plateno)
class Cvn(Vehicle):
def __init__(self,plateno,kml,bedno,dailycost,weeklycost,weekendcost):
Vehicle.__init__(self,plateno,kml,dailycost, weeklycost, weekendcost)
self.bedno=bedno
def __str__(self):
return "Caravan: Plate Number: {0}, km/l: {1}, number of beds: {2}, daily: {3},weekly: {4}, weekend: {5}, Available? {6}".format(self.plateno, self.kml, self.bedno, self.dailycost, self.weeklycost, self.weekendcost, self.avail)
# I N S T A N C E S
# C A R A V A N S Class:Cvn
# (self,plateno,kml,bedno,dailycost,weeklycost,weekendcost)
#------------------
#caravanheaders=["Km/l","Number of beds","Plate number","Daily cost","Weekly cost","Weekend cost"]
cvn1=[12,4,"11-D-144",50,350,200]
cvn2=[10,6,"10-D-965",50,365,285] #values as per Caravan table
cvn3=[11,4,"12-C-143",50,350,200]
cvn4=[15,2,"131-G-111",50,250,185]
cvnslist=[cvn1,cvn2,cvn3,cvn4] #this list contains 4 variables, each representing a list, as above
cvns=[] #this is going to be the list of lists
for i in cvnslist: #this loop creates a list of lists 'cvns'
cvns.append(i)
print("")
print(cvns) #the list of lists
cvninstances=[]
for i in range(len(cvns)):
cvninstances.append(Cvn(cvns[i][2],cvns[i][0],cvns[i][1],cvns[i][3],cvns[i][4],cvns[i][5]))
vehlist.append(Cvn(cvns[i][2],cvns[i][0],cvns[i][1],cvns[i][3],cvns[i][4],cvns[i][5]))
# print(cvninstances) #this shows just that there are objects, but not their attibutes
#for i in cvninstances:
# print(i)
print("")
for i in vehlist:
print("On Vehicles List: ",i)
print("")
print("Initial fleet displayed.")
print("")
#---------------------------------------------------------------------------------
对我来说,不幸的是,这里的大多数类似问题的答案都是更高级的 您将在这里找到有用的信息:
filterfunction,iterable:从iterable的那些元素构造一个列表,函数为其返回true。iterable可以是序列、支持迭代的容器或迭代器。如果iterable是字符串或元组,则结果也具有该类型;否则它总是一个列表。如果function为None,则假定identity函数,即删除iterable中所有为false的元素
您可以创建任意函数以使用lambda进行过滤:
这将为您提供属性attr具有值val的所有对象实例的列表。如果您需要多个可能的值,例如可能的val列表:
您还可以使用Python中非常常见的:
matches = [i for i in obj_list if i.attr == val]
事实上,我认为@sweeneyrod抓住了重点:在我看来,您的问题还在于访问实例的属性,这可以通过以下方式完成:
instance.attribute
如果是这种情况,请再次阅读:
另外,这段代码可以以更优雅的方式重写:
cvninstances.append(Cvn(cvns[i][2],cvns[i][0],cvns[i][1],cvns[i][3],cvns[i][4],cvns[i][5]))
我会首先对cvn_I列表进行重新排序,使参数的顺序与cvn__init__方法的顺序相同,然后将其写成:
cvninstances.append(Cvn(*cvns[i]))
*具有以下含义:获取Cvn[i]中的所有项,并将它们用作参数来实例化Cvn
也许这太高级了——用你自己的话来说——但我认为这绝对是一个你必须知道的模式
[补充]
Cf注释,要过滤,请使用列表理解:
[veh for veh in vehlist if veh.avail==True]
可以这样用更短的方式编写,因为veh.avail包含一个布尔值:
[veh for veh in vehlist if veh.avail]
如果您习惯于数据库查询,这在概念上非常类似:
[/Added]你知道如何获取实例的属性吗?我知道,对于我创建的对象,例如Student1=StudentMary,我可以通过调用Student1来获得名称Mary。name类是Studentself,name…当然这是一个很好的观点,但在我看来,backtoschool正在学习Python,因此,使用理解列表将是一种更自然的方式:类似于:[item for item in lst if item.attr=val]谢谢,我以前使用过instance.attr属性,但在这种情况下,除了通过实例在列表中的位置,我不确定如何访问该实例。如果我想列出avail=True的所有内容,我是否需要通过循环检查每个内容并将它们添加到新列表中,或者有没有更快的方法?与实际编程相比,我更习惯于非常基本的数据库查询,因此这对我来说是一个陡峭的学习曲线!事实上,在编写类似于[veh for veh In vehlist if veh.avail==True]的内容时,您可以同时执行这两种操作。您正在筛选并隐式创建一个新列表来存储结果。关于信息,我发现理解列表更自然,因为它几乎和你在处理集合时可以在数学中写的一样,毕竟“理解”与集合论的公理命名相同:p[veh For veh in vehlist if veh.avail==True]可以减少为[veh For veh in vehlist if veh.avail]。但是我更喜欢明确地写==True子句,这样对你来说就更清楚了;我试试看,谢谢。自然、明确和清晰仍然是我的首要任务,谢谢@返回学校:如果有帮助,请将问题标记为已回答:
[veh for veh in vehlist if veh.avail==True]
[veh for veh in vehlist if veh.avail]