On Fri, 04 May 2018 15:27:02 +0200, Thomas Jollans wrote:

>>>> spamgetter = (lambda seq, i=2, fallback="spam":
> ...                  seq[i] if abs(i) < len(seq) or i == -len(seq) 
> ...                  else fallback)
>>>> spamgetter("abcd", i=-4)
> 'a'
>>>> spamgetter("abcd")
> 'c'
>>>> spamgetter("")
> 'spam'


Doh! Obvious in hindsight. Thanks.

And on my computer, it's only 125% slower than itemgetter.


> Making this work for sequences AND dict-like objects is more
> difficult...

Indeed. At least with dicts you can call .get(). I don't think it is 
necessary to have the one lambda handle both sequence and dict cases. 
Surely when calling it you know whether or not you are looking at a 
sequence or a mapping.



-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to