Reputation: 2924
I have a list of strings and I need to order it by the appearance of a certain character, let's say "+"
.
So, for instance, if I have a list like this:
["blah+blah", "blah+++blah", "blah+bl+blah", "blah"]
I need to get:
["blah", "blah+blah", "blah+bl+blah", "blah+++blah"]
I've been studying the sort()
method, but I don't fully understand how to use the key parameter for complex order criteria. Obviously sort(key=count("+"))
doesn't work. Is it possible to order the list like I want with sort()
or do I need to make a function for it?
Upvotes: 6
Views: 4366
Reputation: 46533
Yes, list.sort
can do it, though you need to specify the key
argument:
In [4]: l.sort(key=lambda x: x.count('+'))
In [5]: l
Out[5]: ['blah', 'blah+blah', 'blah+bl+blah', 'blah+++blah']
In this code key
function accepts a single argument and uses str.count
to count the occurrences of '+'
in it.
As for list.sort(key=count('+'))
, you can get it to work if you define the count
function like this (with operator.methodcaller
):
count = lambda x: methodcaller('count', x) # from operator import methodcaller
Upvotes: 14
Reputation: 90899
You can use -
s = ["blah+blah","blah+++blah","blah+bl+blah","blah"]
print(sorted(s,key=lambda t: t.count('+')))
>>["blah","blah+blah","blah+bl+blah","blah+++blah"]
Upvotes: 0