user1330974 user1330974 - 1 year ago 36
Python Question

How to write lambda function for counting occurrence in a string in Python sort()

I'm trying to write a lambda function (still new to functional programming style of Python). I have a list like this:

cur_list = [b'1z1zzz\r\n', b'1z1z1zzz\r\n', b'1z1z1zzz\r\n', b'zzzz\r\n', b'1zzzz\r\n']

I want to sort the list by the number of occurrence of '1' in each of them. So in the above list, the correct (sorted) solution would be like this:

cur_list = [b'zzzz\r\n', b'1zzzz\r\n', b'1z1zzz\r\n', b'1z1z1zzz\r\n', b'1z1z1zzz\r\n']

What lambda function can be inserted into the following snippet of code to efficiently sort by the occurrence of '1' in a given list of string?

cur_list.sort(key=#####what lambda function to insert here)

Thank you for your answers!

Answer Source

That would be:

lambda x: x.count('1')

Of course, as what you have seems like an array of byte strings, you might want this:

lambda x: x.count(b"1")