简体   繁体   中英

What is keyfunc used for in Python's itertools.groupby() documentation?

In the documentation for itertools.groupby(),

groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)

I see that keyfunc is used as the key to sort the data. What does this keyword refer to?

It's not a keyword. It refers to whatever function you pass to sorted as the key parameter.

It's not mentioned specifically in the section of the docs you linked to, but if you search the page you'll find it in the summary table at the top.

Iterator    Arguments             Results                                        Example
groupby()   iterable[, keyfunc]   sub-iterators grouped by value of keyfunc(v)

In Python documentation, the convention is that optional parts are denoted by square brackets, so here iterable[, keyfunc] means you must pass an iterable, and optionally a parameter called keyfunc . It seems odd that there is no example given as that might have made things clearer.

As they put it in the documentation, "The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged." This is useful, for example for sorting by the second element in a list.

Some examples from someone else who had trouble with this section of the docs, including using a lambda function as the key are given in this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM