Python 按数值对对象实例进行排序

Python 按数值对对象实例进行排序,python,python-3.x,sorting,object,web-scraping,Python,Python 3.x,Sorting,Object,Web Scraping,我正在抓取一个网站的某些值,如名称、价格、股票和评级,并一直在使用这些功能 my_products.sort(key = lambda x: x.return_name()) my_products.sort(key = lambda x: x.return_price()) my_products.sort(key = lambda x: x.return_rating()) my_products.sort(key = lambda x: x.return_s

我正在抓取一个网站的某些值,如名称、价格、股票和评级,并一直在使用这些功能

    my_products.sort(key = lambda x: x.return_name())
    my_products.sort(key = lambda x: x.return_price())
    my_products.sort(key = lambda x: x.return_rating())
    my_products.sort(key = lambda x: x.return_stock())
把它们分类。这一切都很好,很漂亮,只是它没有对价格进行数字排序,它列出了1000、1500、20、200、2000、2500。这不是我想要的。如何更改此排序行为

每种产品的类别:

class Product():
__title = ""
__price = ""
__rating =""
__stock = ""

def __init__(self,title, price, rating, stock):
    self.__title = title
    self.__price = price
    self.__rating = rating
    self.__stock = stock

def toString(self):
    return "Title: {}\nPrice: {}\nRating: {}\nStock: {}\n".format(  self.__title,
                                                                    self.__price,
                                                                    self.__rating,
                                                                    self.__stock)

def return_price(self):
    return self.__price

def return_name(self):
    return self.__title

def return_rating(self):
    return self.__rating

def return_stock(self):
    return self.__stock

只需在键函数中将字符串转换为数字(例如
int
float
):

my_products.sort(key = lambda x: float(x.return_price()))
您还可以更新该方法,使其首先返回一个数字:

def return_price(self):
    return float(self.__price)

您可以通过将
price
设置为一个数字值,而不是一个强制执行当前词典排序的字符串来改变这种行为。通常应为:

__price = 0
...
def __init__(self, title, price, rating, stock):
    self.__price = float(price)

OTOH,您可以强制用户为price传递一个数值,而不是在类中进行清理,方法是对作为price传递的非数值进行
ValueError

在类中编写时,
price
是一个字符串,然后将所有价格像字符串一样进行比较。 您有两个选择:

  • 将价格转换为排序函数:
    my\u products.sort(key=lambda x:float(x.return\u price())

    请注意,您可以通过
    int()
    float()
  • 将价格直接声明为数字(并且不更改排序语法):

  • 在我看来,我会使用选项2来与价值观的含义保持一致。请注意,您应该根据新类型重写函数。
    也许你也可以对你的评级/股票做同样的事情(如果它也是数字的话)

    编辑-字符串比较和排序
    若要比较字符串,请将字符转换为等价的序号,然后从左到右检查int。因此“1000”比“20”低,见下表:

    print('1000 : %d' %sum(ord(i) for i in '1000'))
    print('1500 : %d' %sum(ord(i) for i in '1500'))
    print('20 : %d' %sum(ord(i) for i in '20'))
    
    #output
    1000 : 193
    1500 : 198
    20 : 98
    

    好吧,我不知道排序对数据类型以及数据的价值起作用。谢谢不客气。对于字符串比较,Python将字符转换为其等效的序数值,并从左到右比较整数(请参阅我文章中的更新)。
    print('1000 : %d' %sum(ord(i) for i in '1000'))
    print('1500 : %d' %sum(ord(i) for i in '1500'))
    print('20 : %d' %sum(ord(i) for i in '20'))
    
    #output
    1000 : 193
    1500 : 198
    20 : 98