Ebbinghaus
Ebbinghaus

Reputation: 105

Sorting list of objects in python ( issues with sorted() )

I have a class called Veges:

class Veges: 
     def __init__(self,name,price):
          self.name=name
          self.price=price

     def getName(self):
          return str(self.name)

     def getPrice(self):
          return str("$") + str((self.price))

It can read a .txt file:

Cabbage,13.20
Bean sprouts,19.50
Celery,2.99
Zucchini,3.01
Eggplant,21.80

and create a list that contains my Veges objects:

for i in range( len ( textFile ) ):
        tmpArray = textFile[i].split(',')
        listOfVegetables.append(Veges(tmpArray[0],tmpArray[1]))

The problem comes when I use .sorted():

sorted_Vege = sorted(listOfVegetables, key=lambda x: x.getName())

While I can sort my vegetable objects by name:

Name: Bean sprouts 
Price: $19.50
Name: Cabbage 
Price: $13.20
Name: Celery 
Price: $2.99
Name: Eggplant 
Price: $21.80
Name: Zucchini 
Price: $3.01

I am unable to sort by price (I used x.getPrice()):

Name: Cabbage 
Price: $13.20
Name: Bean sprouts 
Price: $19.50
Name: Eggplant 
Price: $21.80
Name: Celery 
Price: $2.99
Name: Zucchini 
Price: $3.01

I noticed that the double-digit Veges are sorted correctly but the single-digit Veges (Celery & Zucchini) are sorted separately.

How do I fix this?

Just in case, here is how I print my sorted list of objects:

def printVeges(listOfVegetables,index):
    print("Name:", listOfVegetables[index].getName())
    print("Price:", listOfVegetables[index].getPrice())

for i in range(len(sorted_Mov)):
    printVeges(sorted_Vege,i)

Upvotes: 0

Views: 49

Answers (1)

You are sorting based on the string. A workaround can be to convert the string to float and sort based on that. Please check this out:

sorted(listOfVegetables, key=lambda x: float(x.getPrice()[1:]))

x.getPrice()[1:] will get rid of $ and will give digits only.

Upvotes: 1

Related Questions