python中沒有直接對字串排序的方法,下面介紹兩種方法對字串進行排序。
第一種方法,將字串轉換成陣列,對陣列排序後,再轉換成字串。**如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
defmain()
:# 字串
s ="helloworld!"
# 轉換成陣列
l =list
(s)# 對陣列排序,注意,該方法沒有返回值
l.sort(
)# 轉換成陣列
s ="".join(l)
print
(s)# 結果如下:
# !hwdellloor
if __name__ ==
"__main__"
: main(
)
第二種方法,原理和上面的一樣,只不過是使用lambda表示式。先展示**,再詳細解釋**。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
defmain()
: s =
"helloworld!"
s ="".join(
(lambda x:
(x.sort(
), x)[1
])(list
(s))
)print
(s)# 結果如下:
# !hwdellloor
if __name__ ==
"__main__"
: main(
)
來分析分析語句「s = 「」.join((lambda x: (x.sort(), x)[1])(list(s)))」。首先最外層是乙個很基礎的函式,在乙個字串中加入元素(lambda x: (x.sort(), x)[1])(list(s)),該元素是乙個匿名函式。** (lambda x: (x.sort(), x)[1]) 表示函式體,(list(s)) 表示該函式的引數,就是將 s 轉換成 list 傳入到該匿名函式中。匿名函式接收 list,在該函式體內用形參 x 表示。函式體內的 (x.sort(), x)[1] 就是該匿名函式的返回值。為什麼要這麼寫的?因為 python 中 list 的排序方法沒有返回值,所以必須先將 list 排序,然後在返回 list。但是匿名函式只能有一句**,所以用該語句 (x.sort(), x)[1] 來返回排序後的 list。在這個 tuple 中,x.sort() 返回none, 但是此時x已經排好序了,所以第二個 x 已經是有序的 list,最後加乙個[1],表示返回的是有序的 x。
**是網上找的,覺得很精妙,就寫一篇自己的理解。
兩種排序方法(字串 排序 STL)
時間限制 1秒 空間限制 32768k 熱度指數 12801 考拉有n個字串字串,任意兩個字串長度都是不同的。考拉最近學習到有兩種字串的排序方法 1.根據字串的字典序排序。例如 car carriage cats doggies koala 2.根據字串的長度排序。例如 car cats koala...
C語言的兩種字串
c語言中的兩種字串 1.兩種字串的表示 1.字串陣列 char str1 hello char str2 6 hello 注意 在字串 陣列 初始化時sizeof str 的大小應該比你想要的大小 1,因為在作為字串時,會有乙個 0 自動成為字串的元素 上述的例子如果變成 char str2 5 h...
字串的兩種逆序輸出
一 比如輸入 abcd 輸出 dcba include stdio.h include stdlib.h include string.h include char reverse char s p while r p return s int main 二 單詞逆序,比如輸入 you love i...