【问题标题】:Sort a list of custom object with String contains in the object [duplicate]使用对象中包含的字符串对自定义对象列表进行排序[重复]
【发布时间】:2020-01-10 04:33:48
【问题描述】:

我有一个 list 包含自定义 object Box。我想sort 使用object BoxString 属性按字母顺序排列列表。

我试过boxList.sort()boxList.name.sort()。它不起作用。

class Box(object):
   name = “”
   num = 0
   ...
box = Box(name, num)
boxList.append(box)

我在boxList 中有一个框列表。我想按String name 中包含的boxList 的字母顺序对boxList 进行排序。

【问题讨论】:

    标签: python-3.x list sorting object


    【解决方案1】:

    您可以通过对象的name 属性使用自定义key 函数:

    boxList.sort(key = lambda box : box.name)
    

    或者,您可以使用operator.itemgetter 代替lambda 函数:

    from operator import itemgetter
    boxList.sort(key = itemgetter('name'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2015-07-04
      • 2015-08-24
      • 2016-03-13
      • 1970-01-01
      相关资源
      最近更新 更多