itemgetter with default arguments
Serhiy Storchaka
storchaka at gmail.com
Sat May 5 03:31:17 EDT 2018
04.05.18 20:04, Steven D'Aprano пише:
> On Fri, 04 May 2018 09:17:14 -0600, Ian Kelly wrote:
>> On Fri, May 4, 2018 at 7:01 AM, Steven D'Aprano
>> <steve+comp.lang.python at pearwood.info> wrote:
>>> Here are the specifications:
>>>
>>> * you must use lambda, not def;
>>
>> Why? This seems like an arbitrary constraint.
>
> You'll have to ask the two core devs. In my post, in the part you
> deleted, I wrote:
>
> Two senior developers have rejected this feature, saying
> that we should just use a lambda instead.
>
>
> My guess is that they were thinking that there's no need to complicate
> itemgetter for this use-case when it is just as easy to write up a quick
> lambda to do the job.
I prefer using local functions instead of lambdas, but in many concrete
cases it is possible to use a lambda.
Consider a concrete example. You need to sort a list of 2- or 3- element
tuples by the first and third items (third items are strings if
presented). itemgetter(0, 2) doesn't work because some tuples has only 2
items. But you can use the following lambdas:
lambda t: (t[0], t[2] if len(t) > 2 else '')
lambda t: (t[0], t[2]) if len(t) > 2 else (t[0],)
lambda t: (t[0], (t + ('',))[2])
lambda t: t[:1] + t[2:]
The second and the forth options support also the case when there is no
natural minimal value for third items (e.g. for negative integers) or if
you want to order 2-tuples before 3-tuples with empty third item and the
same first item. This isn't possible with itemgetter with default arguments.
If 2-tuples are pretty rare, it may be more efficient to use the
following function:
def sortkey(t):
try:
return t[0], t[2]
except IndexError:
return t[0],
More information about the Python-list
mailing list