Alo*_*aha -1 python python-2.7 python-3.x
我正在尝试根据它们之间的空格在python中排序字符串列表.例如,如果字符串列表是{'hello world', 'hello', 'hello world again', 'hello there'}.
在排序之后,列表应包含第一个位置中空格数最多的字符串,其后包含其他字符串:
{'hello world again', 'hello world', 'hello there', 'hello'}.
Run Code Online (Sandbox Code Playgroud)
此致,Alok
用于list:
>>> list.sort(key=lambda x: x.count(' '), reverse=True)
# list = ['hello world again', 'hello world', 'hello there', 'hello']
Run Code Online (Sandbox Code Playgroud)
用于set:
>>> sorted(set, key=lambda x: x.count(' '), reverse=True)
# ['hello world again', 'hello world', 'hello there', 'hello']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
858 次 |
| 最近记录: |