使用sort方法,可以将list中的元素按自定义属性进行排序 

 

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return 'name:{},age:{}'.format(self.name, self.age)


if __name__ == '__main__':
    p_list = list()

    p_list.append(Person('admin', 15))
    p_list.append(Person('jet', 18))
    p_list.append(Person('Lily', 16))

    for p in p_list:
        print(p,end='; ')
    print()
    # 将list中的数据按照age进行排序
    p_list.sort(key=lambda  x: x.age, reverse=True)  # 默认升序
    for p in p_list:
        print(p, end='; ')
posted on 2019-12-27 21:26  显示账号  阅读(165)  评论(0编辑  收藏  举报