如何根据 python 中的排序功能对商家 ID 进行排序

how to sort the business id based on sort function in python

示例:

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 从高​​到低对评分进行排序

# 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)

您可以使用 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)