Home  >  Article  >  Backend Development  >  python字符串排序方法

python字符串排序方法

WBOY
WBOYOriginal
2016-06-16 08:42:191555browse

本文以实例形式简述了Python实现字符串排序的方法,是Python程序设计中一个非常实用的技巧。分享给大家供大家参考之用。具体方法如下:

一般情况下,python中对一个字符串排序相当麻烦:

一、python中的字符串类型是不允许直接改变元素的。必须先把要排序的字符串放在容器里,如list。

二、python中的list容器的sort()函数没返回值。

所以在python中对字符串排序往往需要好几行代码。

具体实现方法如下:

>>> s = "string"
>>> l = list(s)
>>> l.sort()
>>> s = "".join(l)
>>> s
'ginrst'

对于刚从C/C++等语言转过来的程序员往往会觉得很习惯,因为在C/C++里这些都是一行语句可以搞定的事情。因此,这里给出了一个简单的字符串排序方法。

实现代码如下:

>>> s = "string"
>>> s = "".join((lambda x:(x.sort(),x)[1])(list(s)))
>>> s
'ginrst'

因为用了lambda,稍为有点难理解,但想通了就好了。

希望本文所述对大家的Python程序设计有所帮助

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn