For python's built-in sort()'s key parameter, when to use base class vs object as identifier?

87
April 11, 2022, at 10:40 PM

Let me take an example to clarify what I am talking about.
Say I'm trying to sort() a string s with a key of count (frequency of letters) and in a different case, with a key of lower.
Now, for count, it is required that I use the variable (object) identifier s as follows

"".join(sorted(s, key=s.count))

While, for lower, it is required that I use the base class identifier str as follows

"".join(sorted(s, key=str.lower))

I want to understand why is the usage different in these two examples? And for other methods, how should I understand which identifier to use?

Answer 1

The key parameter takes a function which takes a single argument which is an item in the list. For methods of a class like str, their methods have the signatures

def count(self, x):
    ...
def lower(self):
    ...

In particular, the both have self as the first argument. If you create an instance of the class, the first argument is "bound" to that instance, which basically passes in that instance for self when you call it. Then, calling s.count(x) is the same as str.count(s, x), and str.lower(s) passes in s as self, and it's the same as s.lower().

For the sorting example, passing in key=s.count means you want to sort the string based on the number of times a character appears in the string. For each character x of s, it calls s.count(x).

When key=str.lower, it sorts the string based on the lowercase value of each character, and it is the same as calling x.lower() for each character x in s.

Rent Charter Buses Company
READ ALSO
Get cpu temperature from python? (windows)

Get cpu temperature from python? (windows)

PleaseI have tried every google search result and none of them worked

129
How to go through a Django dictionary in HTML template

How to go through a Django dictionary in HTML template

Im new to Django and I don't really have a clear idea how the Django Template language works but I have a dictionary that is something like this:

107
Python/increase code efficiency about multiple columns filter

Python/increase code efficiency about multiple columns filter

I was wondering if someone could help me find a more efficiency way to run my code

128