我有一个列表列表。我想将数组的元素添加到子列表之一,但我添加的元素取决于数组的长度。
import numpy as np
import numpy.linalg
from numpy import matrix
from scipy.linalg import inv,det,eig
import random
import matplotlib.pyplot as plt
import pylab
from numpy import vstack
from scipy.optimize import curve_fit
from array import array
import copy
def getstabmat(orign, small, specsize, alln):
#FIRST MAKE THE MATRIX
matfound=0
while (matfound==0):
n=orign
A=np.empty((n,n))
I=np.ones((n))
for i in range(0,n):
for j in range(i+1,n):
A[j,i]=random.random()
for i in range(0,n):
for j in range(i+1,n):
A[i,j] = A[j,i]
for i in range(n):
A[i,i]=1
#NOW REMOVE NEGATIVE ELEMENTS AND KEEP SOLVING
allpos=0
while (allpos !=1): #loop for dealing just with getting it positive
x = numpy.linalg.solve(A,I)
if any(tl<small for tl in x): #if any of the solutions in x are negative or small
p=np.where(x==min(x)) # find the most negative solution, p is the position
x=np.delete(x, p, 0)
A=np.delete(A, p, 0)
A=np.delete(A, p, 1)
I=np.delete(I, p, 0)
n=n-1
else:
allpos=1
#now test for stability, only do it once and remove one element before returning to check positiveness.
J=np.empty((n,n)) # make empty jacobian
for i in range (0,n):
for j in range (0,n):
if (i==j): # if we are looking at the diagonal of the matrix, there is a special formula for species dealing with itself
tsum = 0
for k in range (0,n): #for the summation part
tsum = tsum + A[i][k]*x[k] # x is vector of fixed points obtained before
J[i][j] = 1 - A[i][j]*x[i] - tsum
else:
J[i][j] = -A[i][j]*x[i]
#now jacobian at fixed point has been constructed
Jeig, Jvec = eig(J) # get the eigenvalues and eigenvectors
#run through eigenvalues and find out if any of them are positive
if any(tl>0 for tl in Jeig.real): #if any eigenvalues are positive
matfound=0
else:
if ((alln==0 and len(A)==specsize) or alln==1): # if the matrix found has five species
matfound=1
else:
matfound=0
return A, x
def main():
mats=3 #number of matrices to find
orign=15
alln=1 #if alln=1, that means that all sizes of stable matrix should be returned
n=5 # the number of different species wanted in each matrix
small=0.0001 #the fractional size that a species is when it is considered to be extinct
a=0
sortedspec=[[]]*10
specad=[]
while (a<mats): #while all the mats have not been found
print a
A, specfp = getstabmat(orign, small, n, alln) #15 is the original size of matrix to pass to fnc.n is the size that will be returned
a=a+1
print specfp
print len(specfp)
for i in range (0,len(specfp)):
(sortedspec[len(specfp)]).append(specfp[i])
print sortedspec
if __name__ == '__main__':
main()
因此,如果:
specfp = [ 0.78076862 0.79608003 0.50719552]
然后我希望将每个元素添加到列表 sortedspec[3] 中。但是,我最终将数组的每个元素都添加到每个列表元素中。为什么会这样,我可以修复它吗?谢谢你。