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

2024-04-25 20:07:31 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑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或x<;15或y<;15,则将1附加到空列表,如果x或y是其他值,则将零附加到同一空列表。然后我会找到列表的总和,这将是我的计数有多少随机位置落在边缘。你知道吗

这就是我想做的事情:

coordinate=coords_array[x,y]
b=[]
def location(x,y):
    if x>85 or y>85:
        b.appnend(1)
    if x<15 or y<15:
        b.append(1)
    else:
        b.append(0)


print b
print x

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

但我不知道怎么做!你知道吗

有人能教我怎么做吗?你知道吗

谢谢


Tags: orfromimportltgt列表if像素
2条回答

好吧,答案是:

But i am having trouble assigning the array as x and y variables. I want to be able assign each row of the set of random coordinates as an x,y pair so that i can use it in my loop

会是这样的:

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

注:我想你想写这样的函数:

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

否则,正如@TokenMacGuy指出的,在某些情况下,您将插入两个值。你知道吗

注意:从你的问题我知道你想写这段代码是为了学习Python,但是你可以用一种更直接(更有效)的方式,只使用NumPy功能

你可以让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)

请注意,100元素数组的第一个索引是0,最后一个索引是99,因此边的15个位置内的项是0…14和85…99,因此比较中的>=。在上面的代码中,is_close_to_edge是您的列表,带有布尔值。你知道吗

相关问题 更多 >