用惯用的F#方式将一个列表(n个元组或列表)与另一个列表(以及数组)缩放的方式是什么? [英] What would be an idiomatic F# way to scale a list of (n-tuples or list) with another list, also arrays?
问题描述
给出:
let weights = [0.5;0.4;0.3]
let X = [[2;3;4];[7;3;2];[5;3;6]]
我想要的是:
wX = [(0.5)*[2;3;4];(0.4)*[7;3;2];(0.3)*[5;3;6]]
我想知道一种使用列表以及数组的优雅方法.欢迎其他优化信息
what I want is:
wX = [(0.5)*[2;3;4];(0.4)*[7;3;2];(0.3)*[5;3;6]]
would like to know an elegant way to do this with lists as well as with arrays. Additional optimization information is welcome
推荐答案
您编写了一个列表列表,但是您的代码显示了一个元组列表.采取自由进行调整的解决方案将是
You write about a list of lists, but your code shows a list of tuples. Taking the liberty to adjust for that, a solution would be
let weights = [0.5;0.4;0.3]
let X = [[2;3;4];[7;3;2];[5;3;6]]
X
|> List.map2 (fun w x ->
x
|> List.map (fun xi ->
(float xi) * w
)
) weights
根据您对语法的舒适程度,您可能更喜欢像oneliner这样的
Depending on how comfortable you are with the syntax, you may prefer a oneliner like
List.map2 (fun w x -> List.map (float >> (*) w) x) weights X
对于序列(Seq.map2
,Seq.map
)和数组(在Array
模块中),存在相同的库函数.
The same library functions exist for sequences (Seq.map2
, Seq.map
) and arrays (in the Array
module).
这篇关于用惯用的F#方式将一个列表(n个元组或列表)与另一个列表(以及数组)缩放的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!