标签:sort Brown John python Smith Young 列表 排序
本文将讨论的是,如何将一个字符串组成的列表,比如 [‘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
标签:sort,Brown,John,python,Smith,Young,列表,排序 来源: https://blog.csdn.net/linux_tcpdump/article/details/122784845
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。