TP於 2012年9月27日星期四UTC+8上午5時25分04秒寫道: > Hi everybody, > > > > I have tried, naively, to do the following, so as to make lists quickly: > > > > >>> a=[0]*2 > > >>> a > > [0, 0] > > >>> a[0]=3 > > >>> a > > [3, 0] > > > > All is working fine, so I extended the technique to do: > > > > >>> a=[[0]*3]*2 > > >>> a > > [[0, 0, 0], [0, 0, 0]] > > >>> a[0][0]=2 > > >>> a > > [[2, 0, 0], [2, 0, 0]] > > > > The behavior is no more expected! > > The reason is probably that in the first case, 0 is an integer, not a list, > > so Python copies two elements that are independent. > > In the second case, the elements are [0,0,0], which is a list; when Python > > copies a list, he copies in fact the *pointer* to the list, such that we > > obtain this apparently strange behavior. > > > > Is it the correct explanation? > > In these conditions, how to make this list [[0,0,0],[0,0,0]] with "*" > > without this behavior? > > > > Thanks, > > > > TP
def zeros(m,n): for i in xrange(m): for j in xrange(n): a[i][j]=0 return a >>> a=zeros(3,2) >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> I think this is what you want. -- http://mail.python.org/mailman/listinfo/python-list