hi im new to python and was wondering how i can sort by the price going from biggest to smallest but im not sure how to do that without just switching the order of the items and cost in the list
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))
CodePudding user response:
The easiest solution for provided example, once you have all inputs, just sort by price and that's all
sorted_by_ = sorted(data, key=lambda tup: tup[1],reverse=True)
reverse=True will sort descending, since you want from biggest to smallest.
CodePudding user response:
The individual elements of a tuple t=(item, cost) can be accessed using indexing, so that t[0] refers to the item in t and t[1] to the cost in t. Thus, you can replace the condition List[j]<List[j 1] by List[j][1]<List[j 1][1], in order to compare their second components; see code below.
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))