有什么更简洁的方法来计算 J 中列表中元素出现的次数?
这是我的做法(可能很幼稚):
count =: 4 : '# (#~ =&x) y'"1 0 1
换句话说,如果我说 4 count 3 4 4 3 4 7 9
结果是 3
,因为 < code>4 3 在给定列表中出现 3 次。
这非常有效,但我想知道 J 是否提供了一些更简洁的方式来表达这一点。
Here's the (probably naive) way I've done it:
count =: 4 : '# (#~ =&x) y'"1 0 1
In other words, if I say 4 count 3 4 4 3 4 7 9
the result is 3
, because 4
occurs 3 three times in the given list.
This works perfectly, but I wonder whether J offers some more concise way to phrase this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我这样做时,知道我只会有一个列表而不是一个矩阵,我使用:
或者对于列表中的多次搜索:
您的方法仅复制等于 x 的元素,然后对结果进行计数。对这些项进行求和以获得相等就少了一项操作。
When I do this, knowing that I'm only ever going to have a list and not a matrix, I use:
Or for multiple searches in the list:
Your method copies over only the elements that are equal to x, then counts the result. Summing the ones for equality is one less operation.
我同意 MPelletier 提供的算法。既然你要求简洁,那么默契的措辞可能值得一看。这是一个这样的程序,分配了一个名称:
它也可以用作匿名动词,如本例所示:
同义词是
[: +/ =
正如 MPelletier 所说,当您执行以下操作时,该算法就会起作用:想要计算一个简单列表中的原子。 (需要不同方法的类似需求是对形状相似的矩阵列表中匹配的矩阵进行计数。)
I agree with the algorithm provided by MPelletier. Since you're asking for concision, tacit phrasings may be worth looking at. Here's one such program, assigned to a name:
It can also be used as an anonymous verb, as in this example:
A synonym is
[: +/ =
As MPelletier said, this algorithm works when what you want to count are atoms in a simple list. (A similar need that would require a different approach would be counting matrices matched in a list of similarly-shaped matrices.)
我们可能还应该提到 Interval 成员
E.
:所以
例如
We should probably also mention Member of Interval
E.
:so
eg