0

I have a list contains custom object Box. I want to sort the list alphabetically with a String property of the object Box.

I have tried boxList.sort(), boxList.name.sort(). It does not work.

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

I have a list of box in boxList. I want to sort boxList alphabetically by the String name contains in boxList.

YINGFENG
  • 39
  • 6

1 Answers1

1

You can use a custom key function using the name property of your objects:

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

Alternatively, you can use operator.itemgetter instead of a lambda function:

from operator import itemgetter
boxList.sort(key = itemgetter('name'))
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55