我正在根据喜欢的服务类型的排序列表对服务列表进行排序
我有sortingServices函数,该函数应该获取服务列表和喜欢的类型列表(来自用户对象),并且应该返回服务的排序对象列表。
class User :
def __init__(self, id, rates):
self.id = id
self.rates = rates
user1 = User(123 , ["Education" , "food" , "shopping","A"])
class Service :
def __init__(self,id,body,type,fees):
self.id = id
self.body= body
self.type=type
self.fee = fees
service1 = Service(123,"gh","food",12)
service2 = Service(123,"gh","Education",12)
service3 = Service(123,"gh","shopping",12)
service4 = Service(123,"gh","Education",12)
service5 = Service(123,"gh","Education",12)
service6 = Service(123,"gh","shopping",12)
service7 = Service(123,"gh","A",12)
Services= [service1,service2,service3,service3 ,service4,service5,service6,service7]
def sortingServices (services ,user):
sorted(long_list, key=lambda e: (short_list.index(e),e) if e in short_list else (len(short_list),e))
sortingServices(Services , user1)
输出应为:
Services = [service2 , service4 ,service5 , service1 , service3 , service6 , service7 ]
答案 0 :(得分:0)
您需要检查Service.type
是否在User.rates
中并使用该索引。
例如:
Class User :
def __init__(self, id, rates):
self.id = id
self.rates = rates
user1 = User(123 , ["Education" , "food" , "shopping","A"])
class Service :
def __init__(self,id,body,type,fees):
self.id = id
self.body= body
self.type=type
self.fee = fees
service1 = Service(1,"gh","food",12)
service2 = Service(2,"gh","Education",12)
service3 = Service(3,"gh","shopping",12)
service4 = Service(4,"gh","Education",12)
service5 = Service(5,"gh","Education",12)
service6 = Service(6,"gh","shopping",12)
service7 = Service(7,"gh","A",12)
Services= [service1,service2,service3,service4,service5,service6,service7]
def sortingServices (long_list ,short_list):
return sorted(long_list, key=lambda e: short_list.index(e.type) if e.type in short_list else len(short_list))
for i in sortingServices(Services , user1.rates):
print(i.id)
输出:
2
4
5
1
3
6
7