Check if a list of items is sorted according to 2 attributes

I have a list of objects that contains different attributes, like name and index. I have to write a function that check if the index value is given in alphabetical order.

i.e.

items = [item3, item1, item2]
# item1.name = arc; item1.index = 12
# item2.name = banana; item2.index = 27
# item3.name = cards; item3.index = 29
checkAlphaOrder(items) # If index corresponds to alphabetical order, returns True

This is embarrasing, but I can't find a simple way to do so.

1 answer

  • answered 2018-10-11 19:06 0605002

    You need

    all(item[i].name <= item[i + 1].name and item[i].index <= item[i + 1].index
        for i in range(len(items) - 1))
    

    It would compare the name and index values of each consecutive pairs of elements. If each pair appear in ascending order of name and index, the whole list must be sorted.