简体   繁体   中英

Python strange behaviour when sorting a list of tuples

I have a function that looks like the following:

def f(lst, c):

    scored_vals = []
    for i in lst:
        scored_vals += [(i.value/i.weight, i)]
    scored_vals.sort()

    return scored_vals

This function crashes every time it reaches scored_vals.sort() . The argument lst is a list comprised of Item s, where the Item class looks like the following:

class Item():

    def __init__(self, weight=0, value=0):
        self.weight = weight
        self.value = value

And the argument c is just an integer.

The error thrown is below:

    scored_vals.sort()
TypeError: '<' not supported between instances of 'Item' and 'Item'

I find this very strange, because normally when you call python sort, it only compare the first item of each tuple in order to sort the list, so if you create the list yourself like below:

lst = [(201.0, Item()), (350.0, Item()), (202.0, Item()), (100.0, Item()), (500.0, Item()), (203.0, Item())]

Then do:

lst.sort()

It throws no error.

It is because of the method python uses in sorting tuples/lists. If it finds a value that is equivalent, it will go to the second value in the tuple/list. This means that the error will only occur if the tuples have equivalent values as their first index. For example, the following will throw an error:

lst = [(200.0, Item()), (350.0, Item()), (200.0, Item()), (100.0, Item()), (500.0, Item()), (200.0, Item())]
lst.sort()

But this will not:

lst = [(201.0, Item()), (350.0, Item()), (202.0, Item()), (100.0, Item()), (500.0, Item()), (203.0, Item())]
lst.sort()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM