Can get reference of a part of a list?

F

flyaflya

I want make a 2-D array from a list,all elements is references of
list's,like this:
a = [1,2,3,4]
b = [ [1,2], [3,4] ]
when change any elements of a, the elements of b will change too, so I
can use some function for list to change b.
c/c++ can work in this way,I think let b[0] = a[0:2], b[1] = a[2:3],but
it's not reference,it's copy.
 
F

F. Petitjean

Le Fri, 13 May 2005 00:58:49 +0800, flyaflya a écrit :
I want make a 2-D array from a list,all elements is references of
list's,like this:
a = [1,2,3,4]
b = [ [1,2], [3,4] ]
when change any elements of a, the elements of b will change too, so I
can use some function for list to change b.
c/c++ can work in this way,I think let b[0] = a[0:2], b[1] = a[2:3],but
it's not reference,it's copy.
If the original list contains only numeric values of the same type, i.e
only integers or only floats, the Numeric array reshape() function is
what you need :

import Numeric as N
aa = N.array([1, 2, 3, 4])
bb = N.reshape(aa, (2, 2))
print bb
array([[1, 2],
[3, 4]])
bb[0][:] = (7, 8)
aa
array([7, 8, 3, 4])
That is there is only one homogeneous list of values, no copy.
 
T

Terry Reedy

flyaflya said:
I want make a 2-D array from a list,all elements is references of
list's,like this:
a = [1,2,3,4]
b = [ [1,2], [3,4] ]
when change any elements of a, the elements of b will change too, so I
can use some function for list to change b.
c/c++ can work in this way,I think let b[0] = a[0:2], b[1] = a[2:3],but
it's not reference,it's copy.

Look into Numerical Python or Numarray, where slices are views instead of
copies.

TJR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,239
Messages
2,571,200
Members
47,836
Latest member
Stuart66

Latest Threads

Top