这是一个输入列表:[[10;2;10]; [10;50;10]; [10;1;10]]
。
如何过滤每个子列表的第二个元素?
下面是我的代码,当我输出结果时,我得到 [[10;50;10]]
但我想要的是 [2;50;1]
。有办法修复我的代码吗?我真的很想理解 F#。感谢您提前提供的帮助。
let sub =
let input = [[10;2;10]; [10;50;10]; [10;1;10]]
let findIndex input elem = input |> List.findIndex ((=) elem)
let q = input |> List.filter(fun elem -> findIndex input elem = 1)
printfn "%A" q
最佳答案
以下将得到预期的结果:
let second (x:List<int>) = x.[1]
let q = List.map second input
List.map
是一个高阶函数,它通过将函数(第一个参数,此处为返回列表第二个元素的函数 second
)应用到列表(此处为 input
)来创建新列表:
[ [10;2;10]; [10;50;10]; [10;1;10] ]
| | |
second second second <--- mapping function
| | |
V V V
[ 2 ; 50 ; 1 ]
关于list - F# 过滤子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49090918/