Zevvysan
Zevvysan

Reputation: 303

How to sort an a list of currency values as integers?

I have an object with variables "price", "title", and "city". I want to order them by price:

itemlist.sort(key = lambda x: x._price)
for i in itemlist:
    print(i._price, i._title, i._city)

Assuming I have prices ["$1", "$3", "$22", "$12"]. It sorts them ["$1", "$12", "$22", "$3"] when I want it to be ["$1", "$3", "$12", "$22"].

I know it's because price is considered a string and not an int, but what I don't know is how to convert it into an int for the sake of sort.

Upvotes: 0

Views: 422

Answers (2)

pault
pault

Reputation: 43504

You can convert the elements of the list to an int by remove the '$'. One way is by using str.strip():

itemlist.sort(key = lambda x: int(x._price.strip('$'))

Or if you're open to using regular expressions, you could filter out non-digits:

import re
itemlist.sort(key = lambda x: int(re.sub("[^0-9]", "", x._price)))

Where [^0-9] means match anything that is not a digit.

Upvotes: 3

0x5453
0x5453

Reputation: 13589

Naive fix that assumes all price strings start with $:

itemlist.sort(key=lambda x: float(x._price[1:]))

But it's probably a better idea to keep $ out of your prices in the first place, and only add it in when you are printing the price. Store the price as a float or as an int. That will also allow you to do normal math with your prices that you couldn't easily do with strings.

Upvotes: 1

Related Questions