python - 如何按特定字符的计数对字符串列表进行排序?

标签 python list python-2.7 sorting

我有一个字符串列表,我需要按某个字符的出现对其进行排序,比方说 "+"。 因此,例如,如果我有这样一个列表:

["blah+blah", "blah+++blah", "blah+bl+blah", "blah"]

我需要得到:

["blah", "blah+blah", "blah+bl+blah", "blah+++blah"]

我一直在研究sort() 方法,但我并不完全理解如何使用key 参数进行复杂的排序标准。显然 sort(key=count("+")) 不起作用。是否可以使用 sort() 对列表进行排序,或者我是否需要为其创建一个函数?

最佳答案

是的,list.sort可以做到,尽管您需要指定 key 参数:

In [4]: l.sort(key=lambda x: x.count('+'))

In [5]: l
Out[5]: ['blah', 'blah+blah', 'blah+bl+blah', 'blah+++blah']

在这段代码中,key 函数接受一个参数并使用 str.count 来计算其中 '+' 的出现次数。

至于 list.sort(key=count('+')),如果您定义了 count,您可以让它工作> 像这样的功能(使用 operator.methodcaller ):

count = lambda x: methodcaller('count', x) # from operator import methodcaller

关于python - 如何按特定字符的计数对字符串列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30870933/

相关文章:

python - 在linux上与windows上不同的sqlite中存储空的python元组

python - 将 python 字典列表的值合并到单个字典中

python - 如何从列表中解压四个变量?

python - 重定向()和NoReverseMatch

python - 使用带通配符的键创建 Python 字典

python - 如何在列表中修改列表中的元素

list - Erlang 列表理解奇怪的行为

python - python中的字典排序列表

python - 使用 tensorflow 一次切片多个切片

python - 单元测试请求重试python