Numpy Array of Sets

Peter Otten __peter__ at web.de
Sun May 25 11:12:25 EDT 2014


LJ wrote:

> Thank you for the reply.
> 
> So, as long as I access and modify the elements of, for example,
> 
> A=array([[set([])]*4]*3)
> 
> 
> as (for example):
> 
> a[0][1] = a[0][1] | set([1,2])
> 
> or:
> 
> a[0][1]=set([1,2])
> 
> then I should have no problems?

As long as you set (i. e. replace) elements you're fine, but modifying means 
trouble. You can prevent accidental modification by using immutable values 
-- in your case frozenset:

>>> b = numpy.array([[frozenset()]*4]*3)
>>> b[0,0].update("123")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'update'

Or you take the obvious approach and ensure that there are no shared values. 
I don't know if there's a canonical form to do this in numpy, but

>>> a = numpy.array([[set()]*3]*4) 
>>> a |= set()

works:

>>> assert len(set(map(id, a.flat))) == 3*4





More information about the Python-list mailing list