列表的排序和逆序

Posted tanhuan-share

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列表的排序和逆序相关的知识,希望对你有一定的参考价值。

d. 排序和逆序
sort(reverse=False)
reverse()
c = [3,2,5]
c.sort()
print(c)
[2,3,5] #升序

  

 
c.sort(reverse=True)
print(c)
[5,3,2] #降序

 

c.reverse()
print(c)
[2,3,5] #将列表定义的顺序颠倒

  

# 实现列表逆序方法
def reverse_list(cl):
    # 定义一个空列表
    ret_l = []
    i = len(cl) - 1
    while i >= 0:
        ret_l.append(cl[i])  # s += c
        i -= 1
    return ret_l
print(reverse_list(cl))

  

 
# 实现对列表中的字典元素自定义顺序排序
l = [{‘name‘: ‘tom‘, ‘id‘: 3},{‘name‘: ‘tom‘, ‘id‘: 4}]
l.sort(key=lambda d: d[‘id‘])
print(l) # 根据id升序排列,
# >>> [{‘name‘: ‘tom‘, ‘id‘: 3}, {‘name‘: ‘tom‘, ‘id‘: 4}]
l.sort(key=lambda d: d[‘id‘], reverse=True)
print(l) # 根据id降序排序
# >>> [{‘name‘: ‘tom‘, ‘id‘: 4}, {‘name‘: ‘tom‘, ‘id‘: 3}]

  

以上是关于列表的排序和逆序的主要内容,如果未能解决你的问题,请参考以下文章

Python内置函数——排序与逆序

要对一个列表进行顺序,逆序排序,请问使用什么方法?

Python 使用列表的sort()进行多级排序实例演示,list的sort()排序方法使用详解,python3中sort()的cmp自定义排序方法,sort()的逆序倒叙排序方法

归并排序求逆序对

归并排序 逆序对

归并排序:逆序对问题