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']
In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .
Traditionally, information is displayed in sorted order to enable users to easily find the items they are looking for. However, users of different languages might have very different expectations of what a sorted list should look like.
Python does not guarantee that the sort() function will work if a list contains items of different data types. As long as the items can be compared using the < comparison operator, an attempt will be made to sort the list. Otherwise, an error or exception may be generated.
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'))
sorted(l, key=lambda r: r.count('a'))
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