首页 > 解决方案 > 根据另一个短列表python对对象列表进行排序

问题描述

我正在根据最喜欢的服务类型的排序列表对服务列表进行排序

我有 sortServices 函数,它应该接受一个服务列表和一个最喜欢的类型列表(来自用户对象),它应该返回一个排序的服务对象列表。

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 ]

标签: python

解决方案


您需要检查是否Service.typeUser.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

推荐阅读