[Tutor] Best way to store and access a fixed coordinate list
Steven D'Aprano
steve at pearwood.info
Fri Aug 19 06:34:51 CEST 2011
David Crisp wrote:
> Hello,
>
> I have a large grid of numbers 100 * 100
>
> I then randomly select an X and Y to act as a "centre" point.
>
> I have a list of numbers which are coordinate offsets which are then
> applied to the centre point as per:
>
> X = (-2,2),(-4,2),(4,2),(2,2) (The list is about 200 coordinate pairs long)
Two-tuples (x, y) are probably the most light-weight way of doing this.
You then add them like this:
>>> a = (1, 2)
>>> b = (100, 200)
>>> (a[0] + b[0], a[1] + b[1])
(101, 202)
A helper function for adding them together will make life easier:
def add(p1, p2):
"""Return points p1 + p2."""
return (p1[0] + p2[0], p1[1] + p2[1])
And in action:
>>> a = (1, 2)
>>> b = (100, 200)
>>> add(a, b)
(101, 202)
Slightly less light-weight would be a namedtuple, available from Python
2.6 on up. This lets you define a light-weight Point class with named
attributes:
>>> from collections import namedtuple
>>> Point = namedtuple("Point", "x y")
>>> a = Point(23, 42)
>>> a.x
23
>>> a.y
42
Named tuples still behave like tuples, so you can use them like ordinary
tuples:
>>> a[0]
23
>>> a == (23, 42)
True
and the add() helper function will continue to work.
A more heavy-weight solution would be a full-blown Point class, that
defines all the arithmetic operations. Here's one way to do it:
class Point(namedtuple("Point", "x y")):
def __add__(self, other):
return (self[0] + other[0], self[1] + other[1])
__radd__ = __add__
# and similar for subtraction __sub__ and __rsub__
And in action:
>>> a = Point(1, 2)
>>> b = Point(100, 200)
>>> a + b
(101, 202)
The advantage here is that you don't need the helper function, you can
just add Points with the + operator.
--
Steven
More information about the Tutor
mailing list