简体   繁体   中英

python sort list of objects by length of a containing list

I have a class which contains two lists, an int and a string.. which looks something like this

class Something:
    num = 0

    def __init__(self, clu, pro)
        self.clu = clu
        self.rep = []
        self.rep_dis = []
        self.pro = ""

Now in my main I keep a list of Something objects.

something_list = []
tmp_something = Something("this", "that")
tmp_something.rep.append("some")
tmp_something.rep_dis.append("thing")
something_list.append(tmp_something)

How do I sort this list by the length of the objects list rep ?

edit: code segment format

The answer to "how do I sort a list of objects by..." is always "use the key argument to sort ". In this case:

something_list.sort(key=lambda x: len(x.rep))

The key argument is a function which is called for each item in the list, and should return the value according to which you want to 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