pyzor
pyzor

Reputation: 191

Sorting a list based on the occurrence of a character

I want to take in a list of strings and sort them by the occurrence of a character using the python function sort() or sorted(). I can do it in many lines of code where I write my own sort function, I'm just unsure about how to do it so easily in python

In terms of sorted() it can take in the list and the key

l = ['a', 'wq', 'abababaaa']
#I think it's something like this, I know I'm missing something
sorted(l, key = count('a'))

The expected result would be

['wq', 'a', 'abababaaa']

Upvotes: 7

Views: 1232

Answers (2)

zt50tz
zt50tz

Reputation: 155

sorted(l, key=lambda r: r.count('a'))

Upvotes: 5

Sayse
Sayse

Reputation: 43300

You're just missing the lambda for the sorting key so you have a way to reference the list item that needs occurrences of a counted

sorted(l, key = lambda x: x.count('a'))

Upvotes: 7

Related Questions