python - 根据另一个短列表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 ]
解决方案
您需要检查是否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
推荐阅读
- vbscript - 如何使用 VBScript 从 Chrome 进程/标签中获取 URL?
- vector - 如何转换 Vec
到 Vec ? - ksh - 如何在 ksh 中列出所有以“#...”开头的文件名?
- sql - SQL 错误:',' 附近的语法不正确,在插入中使用 select
- python - 将多个帧添加在一起(两个以上)
- python - 如何在使用 python 3 创建虚拟环境时修复看似无休止的循环?
- c# - 在 azure 函数中注入自定义类记录器不会写入控制台
- gstreamer - gstreamer mux原始h264到mp4?
- cypress - UI 元素的自定义子命令
- javascript - 如何使用 Cordova 将 Admob 放入 Vuejs 应用程序中?