Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list of strings by count of a certain character?

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?

like image 289
Pigna Avatar asked Jun 16 '15 14:06

Pigna


People also ask

How do you sort a string based on frequency of character?

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).

How do I sort characters in a string?

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.

Can you sort a list with different data types?

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.


1 Answers

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
like image 175
vaultah Avatar answered Nov 14 '22 21:11

vaultah