numpy 使嵌套的if语句更具可读性和紧凑性

7fhtutme  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(81)

考虑如下所示的1D numpy数组arrRow。它由1和0组成,但重要的特征是该行正好有两个0岛。每个0-岛的右端和左端称为边缘细胞(标记为E),而直接超出每个0-岛的细胞称为边界细胞(标记为B)。

indices: [ 0   1   2   3   4   5   6   7   8   9  10  11  12]

               B   E           E   B       B   E       E   B                 
arrRow : [ 1,  1,  0,  0,  0,  0,  1,  1,  1,  0,  0,  0,  1]

对于一个给定的arrRow,我已经有了代码,可以给我每个Edge单元格和每个Border单元格的索引。在所示的示例中,索引名称和值为:
边缘单元:isl1_start=2, isl1_end=5, isl2_start=9, isl2_end=11
边界单元格:isl1_start-1=1, isl1_end+1=6, isl2_start-1=8, isl2_end+1=12
我需要随机选择两个索引idx1 and idx2,分别取自一个0-island的Edge单元格另一个0-island的Border单元格
在上面的例子中,我有8个选择[idx 1,idx 2]:[2,8], [2,12], [5,8], [5,12], [9,1], [9,6], [11,1], [11,6]
在最左边的0岛从第0列开始的行中,只有6个选择。(如果最右边的0-岛在最后一行单元格中结束,则相同)。
如果最左边的0-岛从第0列开始,而最右边的0-岛在最后一列结束,那么只有4个选择。

问题:有没有一种快速、紧凑的方法来随机选择这两个指数?

我目前使用嵌套的if/elif/else语句来处理所有8+6+6+4 = 24种可能性,如下所示:

if (isl1_start == 0) and (isl2_end_idx == len(arrRow) - 1):
                                               
    rand = random.randint(0, 3)
    if rand == 0:                               
        idx1 = isl1_start
        idx2 = isl2_start - 1
    elif rand == 1:                             
        idx1 = isl1_end
        idx2 = isl2_start - 1            
    elif rand == 2:                     
        idx1 = isl1_end + 1
        idx2 = isl2_start
    elif rand == 3:                       
        idx1 = isl1_end + 1
        idx2 = isl2_end

elif isl1_start == 0:                         
    rand = random.randint(0, 5) 
    if rand == 0:                           
        idx1 = isl1_start
        idx2 = isl2_start - 1
etc...

这很好,但我希望有一个“更严格”的解决方案。我将把上面描述的想法扩展到我有两个以上0-岛的情况下,嵌套的“如果”可能会开始失控。

pbpqsu0x

pbpqsu0x1#

这是边(对于idx1)和边框(对于idx2)的列表。当你一般化它的时候,你只需要把其他的值追加到列表中。

isl1_edges = [isl1_start,  isl1_end]
isl2_borders = [isl2_start-1,  isl2_end+1]

您可以删除所有无效值

N = len(arrRow)
isl2_valid_borders = [idx for idx in isl2_borders if 0 <= idx < N]

而且,正如评论中所建议的那样,使用它来防止你考虑列表的长度。

idx1 = random.choice(isl1_edges)
idx2 = random.choice(isl2_valid_borders)

相关问题