Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要基本Python编程帮助:数组和随机位置_Python_Python 2.7_Numpy - Fatal编程技术网

需要基本Python编程帮助:数组和随机位置

需要基本Python编程帮助:数组和随机位置,python,python-2.7,numpy,Python,Python 2.7,Numpy,考虑一个100X100阵列 i) 在这样的数组中生成数千个随机位置的数组,例如(3,75)和(56,34) ii)计算一个随机位置落在任意(直)边15像素范围内的频率 为了帮助我学习编程语言Python,我正在尝试做上面的问题,我是编程新手 以下是我到目前为止得到的信息: from __future__ import division from pylab import * import math as m from numpy import * from random import randr

考虑一个100X100阵列

i) 在这样的数组中生成数千个随机位置的数组,例如(3,75)和(56,34)

ii)计算一个随机位置落在任意(直)边15像素范围内的频率

为了帮助我学习编程语言Python,我正在尝试做上面的问题,我是编程新手

以下是我到目前为止得到的信息:

from __future__ import division
from pylab import *
import math as m
from numpy import *
from random import randrange

N = 3000
coords_array = array([randrange(100) for _ in range(2 * N)]).reshape(N, 2)
这将创建N个随机位置的数组,不,我正在尝试创建一个循环,如果x>85或y>85或x85: b、 附件(1)
如果xOk,则答案如下:

但是我很难将数组指定为x和y变量。我 希望能够将随机坐标集的每一行指定为 x、 y对,以便我可以在循环中使用它

是这样的:

for pair in coords_array:
    # Do something with the pair
NumPy数组通过让
for
在其主轴上迭代而表现为常规Python序列,这意味着
pair
将包含一个由两个元素组成的数组(在您的示例中)x和y。您也可以这样做:

for x, y in coords_array:
    # Do something with the pair
NB:我想你想写这样的函数:

def location(x,y):
    if x>85 or y>85:
        b.append(1)
    elif x<15 or y<15:
        b.append(1)
    else:
        b.append(0)
def位置(x,y):
如果x>85或y>85:
b、 附加(1)

elif x85或x您可以让numpy为您执行循环:

n = 3000
coords = np.random.randint(100, size=(n, 2))
x, y = coords.T
is_close_to_edge = (x < 15) | (x >= 85) | (y < 15) | (y >= 85)
count_close_to_edge = np.sum(is_close_to_edge)
n=3000
coords=np.random.randint(100,size=(n,2))
x、 y=coords.T
_接近_边=(x<15)|(x>=85)|(y<15)|(y>=85)
count\u close\u to\u edge=np.sum(is\u close\u to\u edge)

请注意,100元素数组的第一个索引为0,最后一个索引为99,因此边缘15个位置内的项目分别为0…14和85…99,因此比较中的
=
。在上面的代码中,
is\u close\u to\u edge
是您的列表,带有布尔值。

只是一个简单提示。您可以像这样生成随机位置:
coords\u array=randint(100,size=(3000,2))
randint
来自
numpy.random
因此,如果列表包含大于85的坐标,您希望列表增加两个元素,否则增加一个元素?这是故意的吗?这是三个几乎相同的问题之一。特别是,你能从中学到什么?
def location(x,y):
    if x>85 or y>85 or x<15 or y<15:
        b.append(1)
    else:
        b.append(0)
def location(x,y):
    if not (15 <= x <= 85) or not (15 <= y <= 85):
        b.append(1)
    else:
        b.append(0)
n = 3000
coords = np.random.randint(100, size=(n, 2))
x, y = coords.T
is_close_to_edge = (x < 15) | (x >= 85) | (y < 15) | (y >= 85)
count_close_to_edge = np.sum(is_close_to_edge)