在 Julia 中循环遍历屏蔽列表的干净方法

Nos*_*All 5 foreach reduction julia

在 Julia 中,我有一个存储在all_neighbors[loc]. 这使我可以使用语法方便地快速循环这些邻居for neighbor in all_neighbors[loc]。这导致可读代码如下:

active_neighbors = 0
for neighbor in all_neighbors[loc]
    if cube[neighbor] == ACTIVE
       active_neighbors += 1
    end
end
Run Code Online (Sandbox Code Playgroud)

精明的读者会发现,这只不过是一种减少。因为我只是在计算活跃的邻居,所以我想我可以使用该count函数在单行中完成此操作。然而,

# This does not work
active_neighbors = count(x->x==ACTIVE, cube[all_neighbors[loc]])
Run Code Online (Sandbox Code Playgroud)

不起作用,因为all_neighbors掩码没有被正确解释为cube数组上的掩码。有谁知道写这个减少的最干净的方法?我想出的另一种解决方案是:

active_neighbors = count(x->x==ACTIVE, [cube[all_neighbors[loc][k]] for k = 1:length(all_neighbors[loc])])
Run Code Online (Sandbox Code Playgroud)

但我真的不喜欢这个,因为它比我开始时的可读性更差。感谢您的任何建议!

Bog*_*ski 5

这应该有效:

count(x -> cube[x] == ACTIVE, all_neighbors[loc])
Run Code Online (Sandbox Code Playgroud)