Arrays? (Or lists if you prefer)

Neil Cerutti horpner at yahoo.com
Sun Oct 22 21:57:15 EDT 2006


On 2006-10-23, Hakusa at gmail.com <Hakusa at gmail.com> wrote:
> Pythonic lists are everything I want in a one dimensional array
> . . .  but I'm trying to do a text adventure and simplify the
> proces by creating a grid as opposed to a tedious list of rooms
> this room connects to.

Not to chase you out of comp.lang.python, but take a stroll by
rec.arts.int-fiction for pointers to a selection of domain
specific programming languages and virtual machines for writing
text adventures.

> So I want to know a good way to do a SIMPLE two dimensional
> array.  Python's lists are a little confusing when it comes to
> how to do this.  I realized that I could do
>
> list = [ [0] * N ] * N

You're right to be suspicious of that construct.

    >>> a = [[0] * 2] * 2
    >>> a
    [[0, 0], [0, 0]]
    >>> a[0][1] = "Oops."
    >>> a
    [[0, 'Oops.'], [0, 'Oops.']]

The problem is that Python lists hold references, not objects,
combined with the behavior of the multiplication operator on
lists.

> but I don't know if it would work because I'm a newbie and only
> understand arrays if they're in grid-like form. And I haven't
> ben thru linear algebra yet, due to my school giving me a few
> set backs I'm allready having to take geometry and allgebra II
> which are meant to be taken one after another at my school, so
> any suggestions  or hints in that direction won't be helpful.
>
> So:
> Way to do SIMPLE array, either internally or externally, with
> Python, please.

The problem wasn't with the construct, but in the way it was
constructed. Just build it up bit by bit, or build it all at once
using range() and then fill it in afterwards.

    >>> b =[range(2), range(2)]
    >>> b
    [0, 1], [0, 1]]
    >>> b[0][1] = "OK."
    >>> b
    [0, 'OK.'], [0, 1]]

A flexible way to do it instead might be to make your data
attributes of objects, instead. It won't be as fast as decoding 
multi-dimensional arrays, but it'll be easier to work with.

Then again, there's Inform, TADS, HUGO, the Z-machine, Glk and
Adrift to consider. ;-)

-- 
Neil Cerutti



More information about the Python-list mailing list