[MATRIX-SIG] reverse of take?

Konrad Hinsen hinsen@ibs.ibs.fr
Mon, 30 Jun 1997 13:51:58 +0200


> Yes. It looks pretty good. The questions that spring to mind are related
> to problems which might arise in implementing a python class which gives
> S vector and data.frame functionality. You can provide a vector in S with
> a vector of character strings and then use the strings to index the original
> vector. Higher dimensional S arrays inherit this property. The cool thing

For non-integer indexing I usually use a dictionary associated with
an array, which stores the mapping from the generalized index to an
integer. It wouldn't be hard to wrap this up in a class. Well, what
the heck, let's do it:

import Numeric

class NamedIndexArray:

    def __init__(self, type, *indices):
	self.array = Numeric.zeros(tuple(map(len, indices)), type)
	self.indices = []
	for index_list in indices:
	    dict = {}
	    self.indices.append(dict)
	    for i in range(len(index_list)):
		dict[index_list[i]] = i

    def __getitem__(self, item):
	if type(item) != type(()):
	    item = (item, )
	index = tuple(map(lambda d, i: d[i], self.indices, item))
	return self.array[index]

    def __setitem__(self, item, value):
	if type(item) != type(()):
	    item = (item, )
	index = tuple(map(lambda d, i: d[i], self.indices, item))
	self.array[index] = value

days = NamedIndexArray(Numeric.Int, ['Jan', 'Feb', 'Mar'])
days['Jan'] = 31
days['Feb'] = 28
days['Mar'] = 31

There's more luxury to add, but that's not difficult either. The only
restriction is that keys should not be tuples, since there is no
difference between a[(2, 3)] and a[2, 3].

> That's not really the hard part at all, since it's been done to death in the
> APL family of languages. See, for example, Budd's book _An APL Compiler_ for

Right, but knowledge about the techniques seems to be limited to that
community, which is pretty small. It takes some effort to dig it out
and write the actual code...
-- 
-------------------------------------------------------------------------------
Konrad Hinsen                          | E-Mail: hinsen@ibs.ibs.fr
Laboratoire de Dynamique Moleculaire   | Tel.: +33-4.76.88.99.28
Institut de Biologie Structurale       | Fax:  +33-4.76.88.54.94
41, av. des Martyrs                    | Deutsch/Esperanto/English/
38027 Grenoble Cedex 1, France         | Nederlands/Francais
-------------------------------------------------------------------------------

_______________
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
_______________