0

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)
Ebbinghaus
  • 95
  • 6
  • 1
    If you use `x.price` as the key instead it will be using the number to compare. Using value from `x.getPrice()` which is string, it will be sorted lexicographically see https://stackoverflow.com/questions/45950646/what-is-lexicographical-order – Krerkkiat Chusap Aug 01 '21 at 10:56
  • Your `getPrice()` returns string thats y – sittsering Aug 01 '21 at 10:58
  • 1
    In string comparison “$20” is less than “$3” because “2” is less than “3”. You should compare these prices as numbers not strings, or 0-fill the price string so you’re comparing “$03” with “$20” – DisappointedByUnaccountableMod Aug 01 '21 at 10:58
  • Does this answer your question? [How to sort a list of strings numerically?](https://stackoverflow.com/questions/3426108/how-to-sort-a-list-of-strings-numerically) – Tomerikoo Aug 01 '21 at 11:05

1 Answers1

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.