Python插入排序,排序string和int

Python insertion sort, sorting string and int

我正在尝试制作对用户输入的产品进行排序的程序,并且我正在尝试实现对字符串进行升序排序(名称)和整数降序排序(代码),有什么建议吗?

class Product:
  def __init__(self, name, code):
    self.name = name
    self.code = code


def insertion_sort(arr):
    for i in range(1, len(arr)):
        z = arr[i]
        j = i-1
        while j >= 0 and z < arr[j]:
            arr[j+1] = arr[j]
            j -= 1
        arr[j+1] = z
    return arr

l = []
p1 = Product('Product1', 2222888)
p2 = Product('NewProduct', 123333)
p3 = Product('Product', 9999999)
p4 = Product('Product1', 2222887)
p5 = Product('TestProduct', 6281732)
l.append([p1.name, p1.code])
l.append([p2.name, p2.code])
l.append([p3.name, p3.code])
l.append([p4.name, p4.code])
l.append([p5.name, p5.code])

print(insertion_sort(l))

您可以使用为此目的排序的python函数

您需要提供排序键

这是更新后的代码。

class Product:
    def __init__(self, name, code):
        self.name = name
        self.code = code


l = []
p1 = Product('Product1', 2222888)
p2 = Product('NewProduct', 123333)
p3 = Product('Product', 9999999)
p4 = Product('Product1', 2222887)
p5 = Product('TestProduct', 6281732)

srted = sorted([p1, p2, p3, p4, p5], key=lambda x: (x.name, -x.code))
print([(i.name, i.code) for i in srted])

x.name-x.code 的关键函数 returns 元组。

所以当两个对象的 x.name 相同时,它会检查 -x.code 是否为负,因此 product 对象将以具有相同 [=11= 的后代方式排序]