簡體   English   中英

如何用字符串和數字對列表進行排序

[英]How do you sort a list with string and numbers

嗨,我是 python 新手,想知道如何按價格從大到小排序,但我不確定如何在不切換列表中的項目順序和成本的情況下做到這一點

Item1 = input("What item do you want to buy? ") # asking what item is
Cost1 = float(input("How much does this item cost? ")) # asking cost of item

Item2 = input("What item do you want to buy? ")
Cost2 = float(input("How much does this item cost? "))

Item3 = input("What item do you want to buy? ")
Cost3 = float(input("How much does this item cost? "))

Item4 = input("What item do you want to buy? ")
Cost4 = float(input("How much does this item cost? "))

Item5 = input("What item do you want to buy? ")
Cost5 = float(input("How much does this item cost? "))

List = [(Item1, Cost1), (Item2, Cost2), (Item3, Cost3), (Item4, Cost4), (Item5, Cost5)] # making a list of other lists

#bubble sort function so it prints in the correct order
def bubble_sort(List):  
    # Outer loop for traverse the entire list  
    for i in range(0,len(List)-1):  
        for j in range(len(List)-1):  
            if(List[j]<List[j+1]):  
                temp = List[j]  
                List[j] = List[j+1]  
                List[j+1] = temp  
    return List  
  
print("Your shopping list is: ",bubble_sort(List))  

提供的示例最簡單的解決方案,一旦您擁有所有輸入,只需按價格排序即可

sorted_by_ = sorted(data, key=lambda tup: tup[1], reverse=True)

reverse=True將按降序排序,因為您想要從最大到最小。

關鍵功能(文檔)

元組 t=(item, cost) 的各個元素可以使用索引訪問,因此 t[0] 指代 t 中的項目,而 t[1] 指代 t 中的成本。 因此,您可以將條件 List[j]<List[j+1] 替換為 List[j][1]<List[j+1][1],以便比較它們的第二個組件; 請參閱下面的代碼。

Item1 = input("What item do you want to buy? ") # asking what item is
Cost1 = float(input("How much does this item cost? ")) # asking cost of item

Item2 = input("What item do you want to buy? ")
Cost2 = float(input("How much does this item cost? "))

Item3 = input("What item do you want to buy? ")
Cost3 = float(input("How much does this item cost? "))

Item4 = input("What item do you want to buy? ")
Cost4 = float(input("How much does this item cost? "))

Item5 = input("What item do you want to buy? ")
Cost5 = float(input("How much does this item cost? "))

List = [(Item1, Cost1), (Item2, Cost2), (Item3, Cost3), (Item4, Cost4), (Item5, Cost5)] # making a list of other lists

#bubble sort function so it prints in the correct order
def bubble_sort(List):  
    # Outer loop for traverse the entire list  
    for i in range(0,len(List)-1):  
        for j in range(len(List)-1):  
            if(List[j][1]<List[j+1][1]):  
                temp = List[j]  
                List[j] = List[j+1]  
                List[j+1] = temp  
    return List  
  
print("Your shopping list is: ",bubble_sort(List))  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM