python中的排序问题——多属性排序

摘要:排序问题是一个经典的问题,在python中,因为有了库函数,排序操作就就更加简单,本文主要讲解如何运用python进行排序操作。比如如何让list按照key1正序排列,同时key2逆序排列;如果按照数组长度排列,如果按照元素最后一个字母序列排列。


1.sort函数说明:

sort函数是list类的一个方法,说明如下:

 sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 cmp(x, y) -> -1, 0, 1

其中,包含三个参数cmp,key,reverse:cmp用于指定排序的大小比较算法;key用于制定排序的维度和优先级别;reverse说明是否是逆序排列(True表示从大到小)


2.实例

 2.1让元组按照第一维度升序,第二维度也是升来排序。(或者都是逆序)



 students.sort(key=lambda l:(l[0],l[1]),reverse=True)
 students.sort(key=lambda l:(l[0],l[1]))


2.2让一组升序,一组数据降序排列:

def mycmp(a,b):
    if a[0]>b[0]:
        return 1
    if a[0]<b[0]:
        return -1
    if a[1]<b[1]:
        return 1
    if a[1]>b[1]:
        return -1
    return 0
if __name__=="__main__":
    #students.sort(key=lambda l:(l[0],l[1]),reverse=True)
    students.sort(cmp=mycmp)


3.python的内置函数sort



a = [5,2,1,9,6]        
>>> sorted(a)                  #将a从小到大排序,不影响a本身结构 
[1, 2, 5, 6, 9] 
>>> sorted(a,reverse = True)   #将a从大到小排序,不影响a本身结构 
[9, 6, 5, 2, 1] 
>>> a.sort()                   #将a从小到大排序,影响a本身结构 
>>> a 
[1, 2, 5, 6, 9] 
>>> a.sort(reverse = True)     #将a从大到小排序,影响a本身结构 
>>> a 
[9, 6, 5, 2, 1] 
注意,a.sort() 已改变其结构,b = a.sort() 是错误的写法! 
>>> b = ['aa','BB','bb','zz','CC'] 
>>> sorted(b) 
['BB', 'CC', 'aa', 'bb', 'zz']    #按列表中元素每个字母的ascii码从小到大排序,如果要从大到小,请用sorted(b,reverse=True)下同 
>>> c =['CCC', 'bb', 'ffff', 'z']  
>>> sorted(c,key=len)             #按列表的元素的长度排序 
['z', 'bb', 'CCC', 'ffff'] 
>>> d =['CCC', 'bb', 'ffff', 'z'] 
>>> sorted(d,key = str.lower )    #将列表中的每个元素变为小写,再按每个元素中的每个字母的ascii码从小到大排序 
['bb', 'CCC', 'ffff', 'z'] 
>>> def lastchar(s): 
       return s[-1] 
>>> e = ['abc','b','AAz','ef'] 
>>> sorted(e,key = lastchar)      #自定义函数排序,lastchar为函数名,这个函数返回列表e中每个元素的最后一个字母 
['b', 'abc', 'ef', 'AAz']         #sorted(e,key=lastchar)作用就是 按列表e中每个元素的最后一个字母的ascii码从小到大排序 
>>> f = [{'name':'abc','age':20},{'name':'def','age':30},{'name':'ghi','age':25}]     #列表中的元素为字典 
>>> def age(s): 
       return s['age'] 
>>> ff = sorted(f,key = age)      #自定义函数按列表f中字典的age从小到大排序  
[{'age': 20, 'name': 'abc'}, {'age': 25, 'name': 'ghi'}, {'age': 30, 'name': 'def'}] 
>>> f2 = sorted(f,key = lambda x:x['age'])    #如果觉得上面定义一个函数代码不美观,可以用lambda的形式来定义函数,效果同上 

### Python属性排序方法 对于Python类的属性进行排序,可以通过多种方式实现。在Python 2中,`sort()`函数有一个`cmp`参数允许传递一个用于自定义多个属性排序的方法,在Python 3中该字段被移除[^1]。 #### 使用内置`sorted()`函数或列表的`sort()`方法配合键函数 一种常见的方式是利用内置的`sorted()`函数或是列表类型的`sort()`方法,并提供一个关键字参数`key`来指定基于哪个属性进行排序。下面是一个简单的例子: ```python class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): # 定义打印对象时显示的内容 return f'Person(name={self.name}, age={self.age})' people = [ Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35) ] # 对象按照年龄升序排列 sorted_people_by_age = sorted(people, key=lambda person: person.age) print(sorted_people_by_age) ``` 这段代码展示了如何创建一个包含姓名和年龄的人类实例列表,并按年龄对其进行排序[^3]。 #### 实现特殊方法以支持自然顺序比较 另一种更灵活的做法是在类内部实现特定于比较操作的方法,比如`__lt__()`(小于),这使得可以直接使用标准库中的排序工具而无需额外指定键函数。当实现了这样的方法之后,就可以像处理基本数据类型那样直接调用`sorted()`或者`.sort()`来进行排序了。 ```python from functools import total_ordering @total_ordering class Product: def __init__(self, id_, price): self.id_ = id_ self.price = price def __eq__(self, other): if not isinstance(other, Product): return NotImplemented return self.price == other.price and self.id_ == other.id_ def __lt__(self, other): if not isinstance(other, Product): return NotImplemented return (self.price, self.id_) < (other.price, other.id_) def __repr__(self): return f"Product(id_='{self.id_}', price={self.price:.2f})" products = [Product('a', 9.9), Product('b', 7.8), Product('c', 9.9)] ordered_products = sorted(products) print(ordered_products) ``` 这里引入了一个装饰器`@total_ordering`来自动生成其他必要的比较方法(`<=`, `>`, `>=`)以便简化编码工作量。 #### 结合多条件排序 如果需要依据多个属性进行复杂排序,则可以在lambda表达式内组合所需属性作为元组返回给`key`参数;也可以通过重写上述提到的特殊方法来完成同样的目的。 ```python students = [ {'name': 'John', 'grade': 88}, {'name': 'Jane', 'grade': 95}, {'name': 'Dave', 'grade': 88} ] # 首先按成绩降序排,再按名字字母表升序排 sorted_students = sorted(students, key=lambda student: (-student['grade'], student['name'])) for s in sorted_students: print(f"{s['name']} got {s['grade']}") ``` 此片段说明了怎样根据两个不同的属性——首先是分数倒序其次是名称正序对学生字典进行了排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值