itemgetter with default arguments

Serhiy Storchaka storchaka at gmail.com
Sat May 5 08:16:50 EDT 2018


05.05.18 12:59, Steven D'Aprano пише:
> On Sat, 05 May 2018 10:31:17 +0300, Serhiy Storchaka wrote:
>> 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:3:2]
> 
> should also work.

Right, this works in this special case (for tuples and 2-items key). You 
can even utilize itemgetter()!

      itemgetter(slice(0, 3, 2))

>>       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:]
> 
> So which of these is the "One Obvious Way"?

Depending on the details of the problem and the background of the 
author, the first or the second options can be the most obvious way. Or 
any other.

>> 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.
> 
> Nobody suggests that itemgetter is a magic wand that ought to solve every
> imaginable problem. There will always be sufficiently complex examples
> where you have to write your own key function.

Right. And it looks to me, that the case in which you want to use 
itemgetter with default arguments is the case where you have to write 
your own key function.




More information about the Python-list mailing list