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?
Sort Characters by Frequency using HashMap – Java Code The easiest approach is to use HashMap to solve this problem. First, we traverse a string and put each character and it's count in a HashMap. After that sort the HashMap by values. The time complexity of this approach is O(nlogn) and it's space complexity is O(n).
The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.
sort() only works for sorting lists. sorted() function is more versatile as we can use it to sort other data types and objects. Today we will see how to sort lists, tuples and dictionaries using the sorted() function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With