Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #47379 > unrolled thread

Re: Idiomatic Python for incrementing pairs

Started byJason Swails <jason.swails@gmail.com>
First post2013-06-08 07:37 -0400
Last post2013-06-08 07:37 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Idiomatic Python for incrementing pairs Jason Swails <jason.swails@gmail.com> - 2013-06-08 07:37 -0400

#47379 — Re: Idiomatic Python for incrementing pairs

FromJason Swails <jason.swails@gmail.com>
Date2013-06-08 07:37 -0400
SubjectRe: Idiomatic Python for incrementing pairs
Message-ID<mailman.2883.1370691449.3114.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

On Sat, Jun 8, 2013 at 2:47 AM, Peter Otten <__peter__@web.de> wrote:
>
> You can hide the complexity in a custom class:
>
> >>> class T(tuple):
> ...     def __add__(self, other):
> ...             return T((a+b) for a, b in zip(self, other))
> ...
> >>> t = T((0, 0))
> >>> for pair in [(1, 10), (2, 20), (3, 30)]:
> ...     t += pair
> ...
> >>> t
> (6, 60)
>
> (If you are already using numpy you can do the above with a numpy.array
> instead of writing your own T.)
>

I do this frequently when I want data structures that behave like vectors
but don't want to impose the numpy dependency on users. (Although I usually
inherit from a mutable sequence so I can override __iadd__ and __isub__).
It seemed overkill for the provided example, though...

All the best,
Jason

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web