using "*" to make a list of lists with repeated (and independent) elements

88888 Dihedral dihedral88888 at googlemail.com
Thu Sep 27 17:24:00 EDT 2012


Tim Chase於 2012年9月27日星期四UTC+8上午6時44分42秒寫道:
> On 09/26/12 17:28, 88888 Dihedral wrote:
> 
> > 88888 Dihedral於 2012年9月27日星期四UTC+8上午6時07分35秒寫道:
> 
> >>>> In these conditions, how to make this list [[0,0,0],[0,0,0]] with "*" 
> 
> >>>> without this behavior?
> 
> >>>     >>> a = [[0]*3 for i in xrange(2)]
> 
> >>>     >>> a[0][0]=2
> 
> >>>     >>> a
> 
> >>>     [[2, 0, 0], [0, 0, 0]]
> 
> > 
> 
> > def zeros(m,n):
> 
> > 	a=[]
> 
> > 	for i in xrange(m):
> 
> > 		a.append([0]*n)
> 
> > 	return a
> 
> > 
> 
> > If  one wants to tranlate to C, this is the style.
> 
> 
> 
> But this is Python, so why the heck would anybody want to emulate
> 
> *C* style?  It could also be written in an assembly-language style,
> 
> COBOL style, or a Fortran style...none of which are particularly
> 
> valuable.
> 
> 
> 
> Besides, a C-style would allocate a single array of M*N slots and
> 
> then calculate 2d offsets into that single array. :-P
> 
> 
> 
> -tkc

a=[1, 2,3] 
b=[a]*4
print b 
a[1]=4
print b

I thnik this is very clear about the situation in entangled references.



More information about the Python-list mailing list