Python 创建具有';1';和'-1';二维numpy数组中的元素
我创建了一个2D numpy数组,并在迭代过程中在随机位置引入了“1”和“-1”。现在,我想要一个指数列表,有那些和负数。 这是我的密码:Python 创建具有';1';和'-1';二维numpy数组中的元素,python,arrays,numpy,Python,Arrays,Numpy,我创建了一个2D numpy数组,并在迭代过程中在随机位置引入了“1”和“-1”。现在,我想要一个指数列表,有那些和负数。 这是我的密码: import math import numpy as np import itertools def function( 250, 10, 50): crystal = np.zeros((250,250)) defect_concentration = np.zeros(50)
import math
import numpy as np
import itertools
def function(
250,
10,
50):
crystal = np.zeros((250,250))
defect_concentration = np.zeros(50)
for k in range(50):
i= np.random.randint(0,250-1,size =2)
while crystal[i[0]][i[1]] != 0:
i = np.random.randint(0,250-1,size =2)
crystal[i[0]][i[1]] = -1
j = np.random.randint(0,250-1,size =2)
while crystal[j[0]][j[1]] !=0:
j = np.random.randint(0,250-1,size =2)
crystal[j[0]][j[1]] = 1
b = []
c = []
dist = math.sqrt(((i[0]-j[0])**2)+((i[1]-j[1])**2))
if dist <= 10:
crystal[i[0]][i[1]] = 0
crystal[j[0]][j[1]] = 0
else:
for x in range(len(crystal)):
for y in range(len(crystal)):
if crystal[x][y] < 0:
b.append((x,y))
elif crystal[x][y] != 0:
c.append((x,y))
导入数学
将numpy作为np导入
进口itertools
def函数(
250,
10,
50):
晶体=np.零((250250))
缺陷浓度=np.零(50)
对于范围(50)内的k:
i=np.random.randint(0250-1,大小=2)
而crystal[i[0]][i[1]!=0:
i=np.random.randint(0250-1,大小=2)
晶体[i[0]][i[1]]=-1
j=np.random.randint(0250-1,尺寸=2)
而晶体[j[0]][j[1]]=0:
j=np.random.randint(0250-1,尺寸=2)
晶体[j[0]][j[1]]=1
b=[]
c=[]
dist=math.sqrt(((i[0]-j[0])**2+((i[1]-j[1])**2))
如果区1 b(1)
名称错误:未定义名称“b”
这不是定义函数的方式:
def function(
250,
10,
50):
您可以清理水晶
索引:
In [512]: crystal[i[0]][i[1]]=10
In [513]: crystal[i[0]][i[1]]
Out[513]: 10.0
更惯用的numpy
:
In [514]: crystal[i[0], i[1]]
Out[514]: 10.0
甚至
In [515]: crystal[tuple(i)]
Out[515]: 10.0
由于i
只有两个数字,这些数字是等价的,但不久以后[…][…]
的索引方式会让你感到痛苦。事实上,你从未定义过b
。很抱歉,我忘了添加这一点