我有一個名爲hab
的列表充當二維數組。在這個列表中,我存儲了一個名爲loc
的類的元素,這就是爲什麼我不使用numpy數組(它不存儲數字)。正在python中沿着列表複製的元素
我想通過循環每個元素來用隨機選取的'loc'填充每個元素。但是,似乎只要我到達行的末尾,程序就會獲取最後一行元素,並將其放入該行的所有其他元素中。這意味着,我結束了尋找這樣的列表清單:
3 3 3 3 3
1 1 1 1 1
2 2 2 2 2
2 2 2 2 2
4 4 4 4 4
的時候其實我想所有這些數字是隨機的(這是打印出每個loc
這是一個特定性狀爲什麼它是數字) 。
這裏是代碼的相關位:
allspec=[] # a list of species
for i in range(0,initialspec):
allspec.append(species(i)) # make a new species with new index
print 'index is',allspec[i].ind, 'pref is', allspec[i].pref
hab=[[0]*xaxis]*yaxis
respect = randint(0,len(allspec)-1)
for j in range(0,yaxis):
for k in range (0,xaxis):
respect=randint(0,len(allspec)-1)
print 'new species added at ',k,j,' is ', allspec[respect].ind
hab[k][j]=loc(k,j,random.random(),allspec[respect])
print 'to confirm, this is ', hab[k][j].spec.ind
for k in range (0,xaxis):
print hab[k][j].spec.ind
printgrid(hab,xaxis,yaxis)
print 'element at 1,1', hab[1][1].spec.ind
在循環中,我確認我已創建的元素是什麼,我想這是與線print 'to confirm, this is ', hab[k][j].spec.ind
,它是罰款在這一點上。只有當循環退出時,它纔會以某種方式填充同一行上的每一個元素。我不明白!
您應該在這裏使用['random.choice'](http://docs.python.org/2/library/random.html#random.choice),或者甚至可能使用['random.sample'](http ://docs.python.org/2/library/random.html#random.sample)。 –
你可以顯示你的'printgrid'功能嗎?很可能你實際上是在創建列表,但是打印錯誤。 – jdotjdot