简体   繁体   English

从二维numpy数组创建具有'1'和'-1'元素的索引列表

[英]Creating a list of Indices having '1' and '-1' elements from a 2D numpy array

I created a 2D numpy array and introduced '1' and '-1' 's at random positions over iterations. 我创建了一个2D numpy数组,并在迭代过程中的任意位置引入了“ 1”和“ -1”。 Now, I want the list of the indices having those ones and minus ones. 现在,我想要包含那些索引和减去索引的索引列表。 Here is my code: 这是我的代码:

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))

but, I am not getting the expected output. 但是,我没有得到预期的输出。

b(1) b(1)

--------------------------------------------------------------------------- NameError Traceback (most recent call last) in () ----> 1 b(1) -------------------------------------------------- ------------------------- NameError Traceback(最近的通话为last)在()----> 1 b(1)

NameError: name 'b' is not defined NameError:未定义名称“ b”

This is not how you define a function: 这不是您定义函数的方式:

def function(
        250,
        10,
        50):

You can clean up the crystal indexing: 您可以清理crystal索引:

In [512]: crystal[i[0]][i[1]]=10
In [513]: crystal[i[0]][i[1]]
Out[513]: 10.0

More idiomatic numpy : 更多惯用的numpy

In [514]: crystal[i[0], i[1]]
Out[514]: 10.0

or even 甚至

In [515]: crystal[tuple(i)]
Out[515]: 10.0

Since i is only 2 numbers these are equivalent, but soon or later the [...][...] style of indexing will bite you. 因为i只有2个数字,这些都是等价的,但不久以后的[...][...]索引的风格会咬你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM