【问题标题】:Sorting list of objects in python ( issues with sorted() )在 python 中对对象列表进行排序( sorted() 的问题)
【发布时间】:2021-10-07 02:30:17
【问题描述】:

我有一个名为 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))

它可以读取一个.txt文件:

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

并创建一个包含我的 Veges 对象的列表:

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

当我使用 .sorted() 时出现问题:

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

虽然我可以按名称对蔬菜对象进行排序:

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

我无法按价格排序(我使用了 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

我注意到两位数的蔬菜排序正确,但一位数的蔬菜(芹菜和西葫芦)是分开排序的。

我该如何解决这个问题?

以防万一,这是我打印排序后的对象列表的方式:

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)

【问题讨论】:

  • 如果您使用x.price 作为键,它将使用数字进行比较。使用来自x.getPrice() 的字符串值,它将按字典顺序排序,参见stackoverflow.com/questions/45950646/…
  • 你的getPrice() 返回字符串就是y
  • 在字符串比较中,“$20”小于“$3”,因为“2”小于“3”。您应该将这些价格作为数字而不是字符串进行比较,或者将价格字符串填充为 0,以便将“$03”与“$20”进行比较
  • 这能回答你的问题吗? How to sort a list of strings numerically?

标签: python


【解决方案1】:

您正在根据字符串进行排序。一种解决方法是将字符串转换为浮点数并以此为基础进行排序。请查看:

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

x.getPrice()[1:] 将摆脱 $ 并只给出数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    相关资源
    最近更新 更多