arrays - F# 三个数组 - 用新值替换原始数组中的唯一值
问题描述
我有三个数组 - 第一个、第二个和第三个。second 包含 first 和 third 的唯一值,包含通过映射到 second 来替换 first 中的新值,如下所示:
module SOQN =
open System
let first = [|"A"; "B"; "C"; "A"; "B"; "A"; "C"; "B"; "C"; "C"; "C"|]
let second = [|"A"; "B"; "C"|]
let third = [|"1"; "2"; "3"|]
let rplc (x:string[]) (y:string[]) (z:string[]) =
first
// |> Array.map (fun w -> Array.iter2 (fun x y -> (if w = x then y)) second third)
let fourth =
rplc first second third
printfn ""
printfn "fourth: %A" fourth
// Expected Result: fourth: [|"1"; "2"; "3"; "1"; "2"; "1"; "3"; "2"; "3"; "3"; "3"|]
// Actual Result: fourth: [|"A"; "B"; "C"; "A"; "B"; "A"; "C"; "B"; "C"; "C"; "C"|]
我的评论行失败,但我不知道为什么?
解决方案
最简单的方法是从第二个和第三个数组创建一个查找表,而不是映射第一个数组的每个元素,并将其用作键。
let first = [|"A"; "B"; "C"; "A"; "B"; "A"; "C"; "B"; "C"; "C"; "C"|]
let second = [|"A"; "B"; "C"|]
let third = [|"1"; "2"; "3"|]
let lookupTbl = Map(Array.zip second third) //create a Map/Dictionary from the zipped values
first
|> Array.map (fun x -> lookupTbl.[x]) //Use the first array's values as keys
//val it : string [] = [|"1"; "2"; "3"; "1"; "2"; "1"; "3"; "2"; "3"; "3"; "3"|]
TryFind
如果您不确定所有密钥都存在,您也可以使用,但在您的情况下似乎没有必要。
您的原始案例不起作用,因为您试图if
用作语句,所以它返回unit
(因为如果 x 不等于 w 会发生什么)。
如果你想更接近你的原始结构,你可以模式匹配而不是 if,然后删除不匹配。Array.collect
将数组数组折叠成一个数组。该match
表达式执行if
代码中的操作,但Some
如果匹配则返回值,None
否则返回值。None
最后我们Some
用Array.choose
.
let rplc (x:string[]) (y:string[]) (z:string[]) =
first
|> Array.collect (fun w ->
Array.map2 (fun x y ->
match (w = x) with
| true -> Some(y)
| _ -> None ) second third)
|> Array.choose id
let fourth =
rplc first second third
printfn ""
printfn "fourth: %A" fourth
// val fourth : string [] =
// [|"1"; "2"; "3"; "1"; "2"; "1"; "3"; "2"; "3"; "3"; "3"|]
// val it : unit = ()
推荐阅读
- python - 如何在 Jupyter Python 中去除饼图之前的文本
- python - 柱状图有多种颜色,用于指示不同的组件
- c# - 如何从我无法直接访问的线程中捕获异常?
- android - 在sqlite中基于多个条件创建触发器
- azure - Azure MobileServiceClient 可以 InsertAsync 但不能 ReadAsync
- docker - Docker 以代码 139 退出;这是什么意思?
- javascript - (TypeError):无法读取未定义的属性“道具”
- php - YII2 moonlandsoft\phpexcel\Excel::import 文件不存在错误
- javascript - 在两个 Javascript 文件之间共享一个常量值
- php - 如何将图像插入媒体目录并为该图像插入帖子数据