基于特定属性对类的对象进行排序

时间:2014-12-18 18:55:18

标签: python list class instance

我想将类的实例存储到文件中,然后读取数据并根据特定属性以升序显示它。

Description of the class: vehicle
Attributes: vehicle type, fuel type, cost
Methods:  GetVdata(), ShowVdata() 

我无法根据成本要求对输出数据进行排序。

 ​import pickle

class vehicle:
    vehicletype = ''
    fueltype = ''
    cost = 0
    def __init__(self, vehicletype = '', fueltype = '', cost = 0):
        self.vehicletype = ''
        self.fueltype = ''
        self.cost = 0
    def GetVdata(self):
        self.vehicletype = raw_input("enter the vehicle type: ")
        self.fueltype = raw_input("enter the fuel type: ")
        self.cost = input("enter the cost of the vehicle: ")
    def ShowVdata(self):
        print "vehicle type : ", self.vehicletype, "\n" , "fuel type: ", self.fueltype , "\n", "cost : ", self.cost
#v = vehicle()
#v.GetVdata()
#v.ShowVdata()


dat1 = vehicle("4 wheeler", "diesel" , 2000000)
dat2 = vehicle("2 wheeler", "petrol" , 100000)
dat1.GetVdata()
dat2.GetVdata()


File = open('transport.dat' , 'wb')
pickle.dump(dat1, File)
pickle.dump(dat2, File)
File.close()

dat1 = vehicle()
File = open('transport.dat','rb')
try:
    while True:
        print"\n"
        output = pickle.load(File)
        output.ShowVdata()
except EOFError:
    File.close()

1 个答案:

答案 0 :(得分:1)

为了根据类的属性对类的对象进行排序,可以使用operator.attrgetter方法。但是,如果您不想导入任何内容,只需将对象的cost属性放在列表中,然后对该列表进行排序。然后根据它找到dump的相应对象。这是一个有效的代码:

import pickle
class vehicle:
    def __init__(self, vehicletype, fueltype, cost):
        self.vehicletype = vehicletype
        self.fueltype = fueltype
        self.cost = cost
    def GetVdata(self):
        self.vehicletype = raw_input("enter the vehicle type: ")
        self.fueltype = raw_input("enter the fuel type: ")
        self.cost = input("enter the cost of the vehicle: ")
    def ShowVdata(self):
        print "vehicle type : ", self.vehicletype, "\n" , "fuel type: ", self.fueltype , "\n", "cost : ", self.cost

dat1 = vehicle("4 wheeler", "diesel" , 2000000)
dat2 = vehicle("2 wheeler", "petrol" , 1000000)
dat3 = vehicle("2 wheeler", "petrol",  5000000)
dat4 = vehicle("4 wheeler", "diesel",  3000000)

data = [dat1, dat2, dat3, dat4]
costs = [i.cost for i in data]
costs.sort()

File = open('transport.dat' , 'wb')

for value in costs:
    for i in range(len(data)):
        if data[i].cost == value:
            pickle.dump(data[i], File)
File.close()

File = open('transport.dat','rb')
try:
    while True:
        print"\n"
        output = pickle.load(File)
        output.ShowVdata()
except EOFError:
    File.close()

现在,如果你运行它,你会得到:

vehicle type :  2 wheeler 
fuel type:  petrol 
cost :  1000000


vehicle type :  4 wheeler 
fuel type:  diesel 
cost :  2000000


vehicle type :  4 wheeler 
fuel type:  diesel 
cost :  3000000


vehicle type :  2 wheeler 
fuel type:  petrol 
cost :  5000000