【问题标题】:Get index value for specific positions in a boolean array in F#获取 F# 中布尔数组中特定位置的索引值
【发布时间】:2020-12-04 10:13:31
【问题描述】:

我有一个仅包含 01 的数组。让我们将此数组称为numbersnumbers 看起来像这样:

val it : int [] =
  [|1; 1; 1; 1; 0; 1; 0; 1; 0; 0; 0; 1; 0; 1; 0; 0; 0; 1; 0; 1; 0; 0; 0; 1; 0;
   0; 0; 0; 0; 1; 0; 1; 0; 0; 0; 0; 0; 1; 0; 0; 0; 1; 0; 1; 0; 0; 0; 1; 0; 0;
   0; 0; 0; 1; 0; 0; 0; 0; 0; 1; 0; 1; 0; 0; 0; 0; 0; 1; 0; 0; 0; 1; 0; 1; 0;
   0; 0; 0; 0; 1; 0; 0; 0; 1; 0; 0; 0; 0; 0; 1; 0; 0; 0; 0; 0; 0; 0; 1; 0; 0;
   ...|]

我想检索出现1 的索引值。例如,在上述数组中,索引01235 等具有1。我想要一个看起来像这样的数组:[| 0; 1; 2; 3; 5; ... |]。我该怎么做?

【问题讨论】:

    标签: f#


    【解决方案1】:
    [| 1; 0; 1; 1; 0 |]
    |> Array.indexed
    |> Array.choose (function (i, n) when n = 1 -> Some i | _ -> None)
    // 0; 2; 3
    

    【讨论】:

      【解决方案2】:

      这可行,虽然我还是 F# 的新手,如果有更优雅的解决方案我很感兴趣

      [| 1; 1; 0; 1; 0; 1 |]
      |> Array.indexed
      |> Array.filter (fun tuple -> snd tuple = 1)
      |> Array.map fst
      |> printf "%A"  
      
      (* prints: [|0; 1; 3; 5|] *)
      

      解释:

      • 展开数组元素得到一个元组数组(index, value)
      • 过滤掉与值上的条件不匹配的元素,
      • 然后只取每个元组的第一部分(索引)

      您还可以将其转换为更通用的辅助函数,可用于任何条件(“谓词”):

      let findAllIndices predicate =
          Array.indexed
          >> Array.filter (snd >> predicate)
          >> Array.map fst
      
      [| 1; 1; 0; 1; 0; 1 |]
      |> findAllIndices (fun x -> x = 1)
      |> printf "%A"
      

      【讨论】:

      • 使用 Array.indexed 代替 Array.mapi
      • @BentTranberg 确实,我错过了这个,谢谢!
      【解决方案3】:

      System.Linq 版本

      open System.Linq
      
      [<EntryPoint>]
      let main argv =
          let it : int [] = [|1; 1; 1; 1; 0; 1;|]
      
          let values = it.Select(fun n i -> if n = 1 then i else -1).Where(fun i -> i >= 0).ToList();
          
          for v in values do
              printf "%A " v
      
          0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-25
        • 2014-02-27
        • 1970-01-01
        • 2021-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多