gpt4 book ai didi

python - 根据另一个短列表对对象列表进行排序 python

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:14 26 4
gpt4 key购买 nike

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

我有 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 ]

最佳答案

您需要检查 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

关于python - 根据另一个短列表对对象列表进行排序 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55587106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com