Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #72006

Re: Numpy Array of Sets

From Peter Otten <__peter__@web.de>
Subject Re: Numpy Array of Sets
Date 2014-05-25 15:26 +0200
Organization None
References <38836877-cd87-44ce-b9df-1eda702e7164@googlegroups.com> <llr5k8$3n6$1@ger.gmane.org> <mailman.10273.1400970363.18130.python-list@python.org> <f55843c2-17f3-4551-a1c6-b608c09fd6d8@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.10294.1401024422.18130.python-list@python.org> (permalink)

Show all headers | View raw


LJ wrote:

> Wolfgang, thank you very much for your reply.
> 
> Following the example in the link, the problem appears:
> 
>>>> A = [[0]*2]*3

You can see this as a shortcut for

value = 0
inner = [value, value]
A = [inner, inner, inner]

When the value is mutable (like your original set) a modification of the 
value shows in all six entries. Likewise if you change the `inner` list the 
modification shows in all three rows.

>>>> A
> [[0, 0], [0, 0], [0, 0]]
>>>> A[0][0] = 5
>>>> A
> [[5, 0], [5, 0], [5, 0]]
> 
> Now, if I use a numpy array:
> 
>>>> d=array([[0]*2]*3)
>>>> d
> array([[0, 0],
>        [0, 0],
>        [0, 0]])
>>>> d[0][0]=5
>>>> d
> array([[5, 0],
>        [0, 0],
>        [0, 0]])
> 
> 
> What is the difference here?

Basically a numpy array doesn't reference the lists, it uses them to 
determine the required shape of the array. A simplified implementation might 
be

class Array:
    def __init__(self, data):
        self.shape = (len(data), len(data[0]))
        self._data = []
        for row in data: self._data.extend(row)
    def __getitem__(self, index):
        y, x = index
        return self._data[y * self.shape[1] + x]

With that approach you may only see simultaneous changes of multiple entries 
when using mutable values.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Numpy Array of Sets Luis José Novoa <luisjosenovoa@gmail.com> - 2014-05-24 15:05 -0700
  Re: Numpy Array of Sets Robert Kern <robert.kern@gmail.com> - 2014-05-24 23:14 +0100
  Re: Numpy Array of Sets Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> - 2014-05-25 00:25 +0200
    Re: Numpy Array of Sets LJ <luisjosenovoa@gmail.com> - 2014-05-25 05:29 -0700
      Re: Numpy Array of Sets Peter Otten <__peter__@web.de> - 2014-05-25 15:26 +0200
        Re: Numpy Array of Sets LJ <luisjosenovoa@gmail.com> - 2014-05-25 07:14 -0700
          Re: Numpy Array of Sets Peter Otten <__peter__@web.de> - 2014-05-25 17:12 +0200
            Re: Numpy Array of Sets LJ <luisjosenovoa@gmail.com> - 2014-05-25 08:17 -0700

csiph-web