前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >三种python 列表排序方法

三种python 列表排序方法

作者头像
用户8418197
发布2022-02-17 21:33:45
7780
发布2022-02-17 21:33:45
举报
文章被收录于专栏:howtouselinuxhowtouselinux

本文将讨论的是,如何将一个字符串组成的列表,比如 'abc','cba','bac' ,按照特定的条件(比如首字母、尾字母、或者长度)灵活的排序?

目录

直接排序

由一些字符串组成的 list ,sort( )方法可以直接用来对字符串排序:

a = "John Smith", "Alice Young", "John Scott Brown"

a.sort()

a

'Alice Young', 'John Scott Brown', 'John Smith'

注意,这里 sort 方法是原位排序(in-place sort),也就是直接更改了原对象。

按其中一部分排序

在上面的例子里,如果我想按照空格后面的姓排序,该怎么写?sort 方法有一个可选参数key,接收一个函数,这个函数将待排序的对象重新处理后,作为新的排序依据,传给 sort。

这个函数用 lambda 匿名函数表示最方便。

a = "John Smith", "Alice Young", "John Scott Brown"

a.sort(key=lambda x:x.split()-1)

a

'John Scott Brown', 'John Smith', 'Alice Young'

这个例子里,按照 Brown、Smith、Young 排序

按长度排序

key 也可以定义为内置函数,比如 len

a = "John Smith", "Alice Young", "John Scott Brown"

a.sort(key=len)

a

'John Smith', 'Alice Young', 'John Scott Brown'

a.sort(key=len, reverse=True)

a

'John Scott Brown', 'Alice Young', 'John Smith'

python sort list

how to get the length of a python list

how to use the python list pop method

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
作者已关闭评论
0 条评论
热度
最新
推荐阅读
目录
  • 直接排序
  • 按其中一部分排序
  • 按长度排序
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档