英文:
How to implement SQL ORDER BY like funtionality in python?
问题
我有一个类似这样的对象列表
time_slots = ['<TimeSlot: capacity: 1, number: 5>',
'<TimeSlot: Room: capacity: 3, number: 2>',
'<TimeSlot: capacity: 4, number: 1>',
'<TimeSlot: capacity: 4, number: 6>',
'<TimeSlot: capacity: 4, number: 1>',
'<TimeSlot: capacity: 4, number: 3>']
我想根据number和capacity对上述对象进行排序。
基本上,我想实现这个:
ORDER BY number, capacity;
我可以通过类似以下方式访问每个对象的属性:
time_slots[i].number
我需要在Python中实现这个逻辑。有人可以帮我吗?
编辑:这是实际问题的简化版本。请参阅实际问题
stackoverflow.com/q/75664227/20443528
英文:
I have a list of objects like this
time_slots = ['<TimeSlot: capacity: 1, number: 5>',
'<TimeSlot: Room: capacity: 3, number: 2>',
'<TimeSlot: capacity: 4, number: 1>',
'<TimeSlot: capacity: 4, number: 6>',
'<TimeSlot: capacity: 4, number: 1>',
'<TimeSlot: capacity: 4, number: 3>']
I want to sort the above object on the basis of number and capacity.
Basically, I want to implement this-
ORDER BY number, capacity;
I can access the properties of every object by using something like-
time_slots[i].number
I have to implement this logic in python. Can someone please help me with this?
Edit: This is a simplified version of the actual problem. Please see the actual problem
stackoverflow.com/q/75664227/20443528
答案1
得分: 2
你可以将一个方法传递给 sorted
函数,以指定要按哪些属性排序并返回为元组。类似以下的代码应该可以工作:
sorted(time_slots, key=lambda x: (x.number, x.capacity))
英文:
You can pass a method to the sorted
function to specify the attributes to sort by returned in a tuple. Something like this should work:
sorted(time_slots, key=lambda x: (x.number, x.capacity))
答案2
得分: 0
你必须包含 quotes
以使其成为有效的Python代码:
l=['<TimeSlot: capacity: 4, number: 1>', '<TimeSlot: Room: capacity: 3, number: 2>', '<TimeSlot: capacity: 4, number: 6>','<TimeSlot: capacity: 4, number: 1>', '<TimeSlot: capacity: 1, number: 5>', '<TimeSlot: capacity: 4, number: 3>']
sorted(l,key=lambda x:x.split('capacity')[1][2])
解释:
我们通过关键字 capacity
进行分割,分割后的列表中将会有 2
个元素。然后您必须对它们进行索引以获取其中的数值。
英文:
You have to include quotes
to make it a valid python:
l=['<TimeSlot: capacity: 4, number: 1>', '<TimeSlot: Room: capacity: 3, number: 2>', '<TimeSlot: capacity: 4, number: 6>','<TimeSlot: capacity: 4, number: 1>', '<TimeSlot: capacity: 1, number: 5>', '<TimeSlot: capacity: 4, number: 3>']
sorted(l,key=lambda x:x.split('capacity')[1][2])
#
['<TimeSlot: capacity: 1, number: 5>',
'<TimeSlot: Room: capacity: 3, number: 2>',
'<TimeSlot: capacity: 4, number: 1>',
'<TimeSlot: capacity: 4, number: 6>',
'<TimeSlot: capacity: 4, number: 1>',
'<TimeSlot: capacity: 4, number: 3>']
Explanation
:
We are splitting by 'capacity'
keyword, there will be 2
elements in the list formed after split. Then you have to index them to get the numeric value from it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论