tags:

views:

177

answers:

5

Hi

I have a list of tuples (each tuple item is a pair of integers) and I would like to add a constant value to each tuple in the list.

For example [(x0,y0),(x1,y1),...] -> [(x0+xk,y0+yk),(x1+xk,y1+yk)....]

xk,yk are constants

How do I do this

Thanks

A: 

an example to add things to tuple

>>> a=(1,2)
>>> a+=(1,)
>>> a
(1, 2, 1)

you can adapt it to your requirement

ghostdog74
Even so, if you're planning on appending things, it may be advantageous to use a list rather than a tuple.
avpx
Hi ghostdog, sorry I was not more specific, I would like to add a constant value to every item in the tuple .ie [(x0,y0),(x1,y1),...] -> (x0+xk,y0+yk),(x1+xk,y1+yk)....]Thanks
mikip
+2  A: 

Use numpy, e.g.,

>>> import numpy as np
>>> a = np.array([[1,2],[2,3]])
>>> print a
[[1 2]
 [2 3]]
>>> print a + 2
[[3 4]
 [4 5]]
nikow
+3  A: 
>>>> l = [(1,2), (3,4)]
>>>> for i, e in enumerate(l):
....     l[i] = (e[0]+xk, e[1]+yk)

As always, untested. ;-)

If you don't need to do it in place, it's even simpler

>>>> l = [(e[0]+xk, e[1]+yk) for e in l]
jae
+3  A: 

You can't add a constant to a tuple because tuples are immutable.

You can however create a new tuple from the old one by incrementing it's values. See jae's answer for the basics of how to do this.

You should note however that you will be creating a lot of new tuples in this loop and this may not be a very efficient way of handling this. You should investigate numpy (as suggested by nikow) or perhaps using lists or coordinate objects instead of tuples.

JonahSan
Thanks for providing the background info that I omitted. :-D (Yes, I upvoted it too).
jae
A: 

Solution:

l = [(i[0]+k[0], i[1]+k[1]) for i in l]

Test code:

l = [(1,2), (3,4)]
k = (10, 100)
l = [(i[0]+k[0], i[1]+k[1]) for i in l]
assert l == [(11, 102), (13, 104)]
van