Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 792
pyzor Avatar asked Aug 15 '19 11:08

pyzor


People also ask

How do you sort a list in Python by character?

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

What is character sorting?

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.

Can you sort a list with different data types?

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.


2 Answers

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'))
like image 155
Sayse Avatar answered Oct 27 '22 00:10

Sayse


sorted(l, key=lambda r: r.count('a'))
like image 25
zt50tz Avatar answered Oct 27 '22 00:10

zt50tz