Home > front end >  Keep getting a error when I try and sort a list, says "TypeError: '<' not supporte
Keep getting a error when I try and sort a list, says "TypeError: '<' not supporte

Time:03-26

toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]

prices = [2, 6, 1, 3, 2, 7, 2]
num_two_dollar_slices = prices.count(2)
print(num_two_dollar_slices)

num_pizzas = len(toppings)
print(num_pizzas)
print("We sell "  str(num_pizzas) " different kinds of pizza!")

pizza_and_prices =  [2, "pepperoni", 6, "pineapple", 1, "cheese", 3, "sausage", 2, "olives", 7, "anchovies", 2, "mushrooms"]
print(pizza_and_prices)

*pizza_and_prices.sort()
print(pizza_and_prices)*

What do I need to change in order for my list of pizza_and_prices to be sorted into alphabetical order?

CodePudding user response:

The problem is, you have both strings and integers as part of the same list. When python is trying to sort them, it is not able to, because it can't compare strings with int. Hence, you should try using a 2D list. Like this.

pizza_and_prices = [[ 6,"pineapple"], [2, "pepperoni"]]
pizza_and_prices.sort(key=lambda pp:pp[0])

CodePudding user response:

You can create a dictionary and then sort the pizzas by prices:

toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
prices = [2, 6, 1, 3, 2, 7, 2]
price_list = dict(zip(toppings, prices)) #Create a dictionary
price_list = {k: v for k, v in sorted(price_list.items(), key=lambda item: item[1])} # Sort the dictionary by prices

Output:

{'cheese': 1, 'pepperoni': 2, 'olives': 2, 'mushrooms': 2, 'sausage': 3, 'pineapple': 6, 'anchovies': 7}

CodePudding user response:

You could do it like this:

pizza_and_prices =  [2, "pepperoni", 6, "pineapple", 1, "cheese", 3, "sausage", 2, "olives", 7, "anchovies", 2, "mushrooms"]
p = []
for e in sorted(list(zip(pizza_and_prices[1::2], pizza_and_prices[::2]))):
    p.extend(e[::-1])
pizza_and_prices[:] = p
print(pizza_and_prices)

Output:

[7, 'anchovies', 1, 'cheese', 2, 'mushrooms', 2, 'olives', 2, 'pepperoni', 6, 'pineapple', 3, 'sausage']

Explanation:

Create a new list of tuples such that each tuple is (description, price). Builtin sort can handle that and will sort it lexicographically (initially). Then unpack that sorted list (of tuples) and rebuild the original list.

CodePudding user response:

You should dictionary like this

pizza_and_prices = {
"pepperoni":2, "pineapple":6, 
"cheese":1, "sausage":3, 
"olives": 2, "anchovies": 7,  
"mushrooms":2, 
}

Sorting dictionary

pizza_and_prices = dict(sorted(pizza_and_prices.items(), key=lambda x: x[1]))

if you don't know what is dictionary
you can watch this video

https://youtu.be/2IsF7DEtVjg

  • Related