如何根据python中的排序功能对业务ID进行排序

Posted

技术标签:

【中文标题】如何根据python中的排序功能对业务ID进行排序【英文标题】:how to sort the business id based on sort function in python 【发布时间】:2021-06-07 11:53:32 【问题描述】:

例子:

enter code here
businesses: [
    Business(id=1, rating=4.0, vegan_friendly=True, price=4, distance=10.0),
    Business(id=2, rating=2.5, vegan_friendly=False, price=2, distance=5.0),
    Business(id=3, rating=4.5, vegan_friendly=False, price=1, distance=1.0),
    Business(id=4, rating=3.0, vegan_friendly=True, price=2, distance=3.4),
    Business(id=5, rating=4.5, vegan_friendly=true, price=1, distance=6.3),
    Business(id=6, rating=3.5, vegan_friendly=True, price=2, distance=1.2),
]

根据id从高到低排序

【问题讨论】:

你已经尝试了什么? 它已经按 id 排序,如果您想按评级排序,请澄清/确认?并显示和编辑问题以显示您尝试过的代码。 【参考方案1】:
# To sort the list in place...
businesses.sort(key=lambda x: x.id, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(businesses, key=lambda x: x.id, reverse=True)

【讨论】:

当我想使用带有少量过滤器的代码时,它将如何工作 def filter_and_sort_businesses(businesss: List[Business], only_vegan_friendly: bool = False, max_price: Optional[int] = None, max_distance: Optional [float] = None, ) -> List[int]: @komal vyas 请问你是怎么解决这个问题的【参考方案2】:

您可以使用python内置方法sorted并提供排序key

businesses = [
    Business(id=1, rating=4.0, vegan_friendly=True, price=4, distance=10.0),
    Business(id=2, rating=2.5, vegan_friendly=False, price=2, distance=5.0),
    Business(id=3, rating=4.5, vegan_friendly=False, price=1, distance=1.0),
    Business(id=4, rating=3.0, vegan_friendly=True, price=2, distance=3.4),
    Business(id=5, rating=4.5, vegan_friendly=true, price=1, distance=6.3),
    Business(id=6, rating=3.5, vegan_friendly=True, price=2, distance=1.2),
]
businesses_sorted = sorted(businesses, key=lambda business: business.id)

反向列表使用reverse标志:

businesses_sorted_reversed = sorted(businesses, key=lambda business: business.id, reverse=True)

【讨论】:

以上是关于如何根据python中的排序功能对业务ID进行排序的主要内容,如果未能解决你的问题,请参考以下文章

如何根据另一个表中的索引序列对列中的名称进行排序?

根据 Woocommerce 中的运输姓氏按字母顺序对订单 ID 进行排序

如何根据另一个数组的顺序对对象数组进行排序?

如何根据数组的成员对集合进行排序

python怎么对字典进行排序

根据另一个集合项目对项目进行排序