【问题标题】:Python: automating the generation of a variable number of if statementsPython:自动生成可变数量的 if 语句
【发布时间】:2018-08-30 15:02:58
【问题描述】:

我有两个类似的 numpy 数组,它们代表坐标:

import numpy as np
x=np.array([1,3,2,4,6,5,4,1])
y=np.array([4,4,3,2,2,1,3,5])

我也有n方块:

s1 -> x=0 to 3, y=0 to 3
s2 -> x=3 to 6, y=3 to 6
s3 -> ...
s4 -> ...

我想计算每个正方形内的点数。这归结为评估n 不等式。

我的方法很冗长并且(可能)效率低下:

count1=0
count2=0
count3=0
count4=0
for j in range(0, len(x)):
    #Square 1
    if x[j]<=3 and y[j]<=3:
        count1+=1
    #Square 2
    if x[j]<=3 and y[j]>3 and y[j]<=6:
        count2+=1
    #Square 3
    if x[j]>3 and x[j]<=6 and y[j]<=3:
        count3+=1
    #Square 4
    if x[j]>3 and x[j]<=6 and y[j]>3 and y[j]<=6:
        count4+=1

给定我的两个数组,返回:

In[1]: count1, count2, count3, count4
Out[1]: (1, 3, 4, 0)

我真正的问题包括可变数量的方格(可能是 6 个,也可能是 36 个,等等)。

有没有一种方法可以自动生成count 变量以及if 语句的数量和边界?

【问题讨论】:

  • 你不能把方块的边界放在一个循环中吗?

标签: python numpy for-loop if-statement inequalities


【解决方案1】:

你没有列出你的整个代码,所以不清楚你到底想做什么。在任何情况下,你都可以用一个元组来描述每个方格

square_n = ((x1, x2), (y1, y2))

并将它们放入字典中,其中键是这个元组,值是计数。然后,像

for square in squares_dict:
    (x1, x2), (y1, y2) = square
    if x1<a<x2 and y1<b<y2: # whatever criterion you have
        squares_dict[square] += 1

【讨论】:

    【解决方案2】:

    这是一个数组非常有用的情况。

    您可以创建一个计数数组,并为该数组编制索引,而不是创建单独的 countn 变量(因此 count0 变为 count[0]count1count[1],等等)。

    现在的诀窍是将 x 和 y 坐标映射到特定的计数数组索引,您只需进行一些数学运算即可。即,如果正方形是 3x3 并排列成一个大矩形,那么 x // 3 + (y // 3) * num_squares_per_row 会为您提供索引。

    如果您要计算的区域不统一,因此您无法得出一个简单的数学方程式,您可以随时制作一个字典,将您要计算的事物映射到它们的索引在count 数组中,并使用它来确定在给定特定输入的情况下要增加的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 2020-08-20
      • 2019-08-20
      • 2018-07-31
      • 2016-04-05
      • 2011-10-25
      • 2016-08-17
      相关资源
      最近更新 更多