Python 按字符串排序

2018-04-20
标签: PYTHON
本文发布至今已有5年零335天,可能不再适用,请谨慎对待。

直接排序

由一些字符串组成的 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']

这个例子里, split() 按空格分离字符串, [-1] 则取出每组里的最后一部分。最终结果是按照每个人的姓氏字母排序,也就是 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

欢迎转载本文,惟请保留 原文出处 ,且不得用于商业用途。
本站 是个人网站,若无特别说明,所刊文章均为原创,并采用 署名协议 CC-BY-NC 授权。