本文介绍了Array2D 到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 0 和 1 的 Array2D:

I have Array2D of 0 and 1:

let rnd = System.Random()
let a = Array2D.init n n (fun i j  -> int(System.Math.Round(rnd.NextDouble() / index)) )

我需要计算1"元素的数量,例如:

I need to calculate the count of '1'-elements, something like:

a |> Array.filter (fun x -> x == 1)

但是 'a' 是 Array2D(不是 Array)所以我只是想知道是否有将 Array2D 转换为 Array 的标准方法?

But 'a' is Array2D (not Array) so I'm just wondering if there is a standard way to transform Array2D to Array?

推荐答案

这里有一个简单的方法,使用 [,] 实现 ienumerable

Here is one easy way, using the fact that [,] implements ienumerable<_>

a |> Seq.cast<int> |> Seq.filter (fun x -> x == 1)

但如果你只需要计数,你可以做

but if you only need the count you can do

a |> Seq.cast<int> |> Seq.sum

因为 0 项不会添加到总和中,而您要计算的项仅为 1

as the 0 terms won't add to the sum and the terms you want to count are just 1

这篇关于Array2D 到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 00:17