从最贵的到最便宜的(PYTHON)整理产品

时间:2021-03-13 12:34:53

标签: python

我正在尝试整理一个包含从最贵到最便宜的产品的列表。我只成功识别了最贵的一款,我不知道如何识别中间款或最便宜的一款。如果有人可以帮助我,我将非常感激。 这是我的代码:

def sort_prices(list_of_tuples):
    i = 0
    count = 0
    the_new_list = [] # the final list with the products
    for prices in list_of_tuples:
        price = float(prices[1])
        count = 0
        for check_big in list_of_tuples: ## for loop to check if that the bigger price
            if price > float(check_big[1]):
                count += 1
        if count == len(list_of_tuples) - 1:
            the_new_list += prices
        i += 1

    print(the_new_list)
def main():
    products = [('milk', '5.5'), ('bread', '9.0'), ('candy', '2.5')]
    sort_prices(products)
if __name__ == "__main__":
    main()

3 个答案:

答案 0 :(得分:1)

def takeSecond(elem):
    return float(elem[1])

products = [('milk', '5.5'), ('bread', '9.0'), ('candy', '2.5')]
products.sort(key=takeSecond)
products
>>> [('candy', '2.5'), ('milk', '5.5'), ('bread', '9.0')]

答案 1 :(得分:1)

您有多种选择:

使用 Python 内置函数:您可以使用 Python 的内置 sorted() 或 sort() 函数。这两个函数都采用一个键,该键可以设置为命名函数或匿名 lambda 函数,以确定列表的排序方式。最后, reversed=True 参数确保它按降序排序。

def sort_prices(list_of_tuples):
    the_new_list = sorted(list_of_tuples, key= lambda x: float(x[1]), reverse= True)
    print(the_new_list)

#[('bread', '9.0'), ('milk', '5.5'), ('candy', '2.5')]

制作自己的排序函数:如果您尝试制作自己的排序函数,则需要决定要使用哪种排序算法。有几种:冒泡排序、插入排序、选择排序、归并排序、快速排序等。下面是如何为您的元组列表实现插入排序。

def sort_price(list_of_tuples):
    """Uses insertion sort algorithm. Traverses the list, comparing each item to the one
    before it and swapping it repeatedly with the previous item back through the preceding
    sorted portion of the list until it finds its rightful place."""

    my_list = list(list_of_tuples) #makes a copy of list_of_tuples
    for i in range(len(my_list)):
        j = i
        while float(my_list[j][1]) < float(my_list[j-1][1]) and j > 0:
            my_list[j-1], my_list[j] = my_list[j], my_list[j-1] #swap
            j-=1
    my_list.reverse() #to get it in descending order
    print(my_list)

#[('bread', '9.0'), ('milk', '5.5'), ('candy', '2.5')]

答案 2 :(得分:1)

您可以使用 key 对列表进行排序,如下所示:

products = [('milk', '5.5'), ('bread', '9.0'), ('candy', '2.5'), ('candy2', '20.5')]
products.sort(key=lambda x: float(x[1]))