F#模式过滤

Shi*_*Pie 3 f#

有人可以告诉我如何在列表包含特定号码时过滤掉列表.例如,如果子列表包含2,那么我想要第三个值.

let p = [ [0;2;1]; [7;2;5]; [8;2; 10]; [44; 33; 9]]
//Filtered List: [1;5;10]
let q = p |> List.filter(fun((x,y):int List)  (List.item 2 x) = 1,  (List.item 3 y))
Run Code Online (Sandbox Code Playgroud)

上面是我的代码到目前为止.我知道它的错误,但似乎无法在代码中弄明白.

小智 6

s952163的答案是正确的,但是,List.choose会更好.

p
|> List.choose (fun list ->
  if List.contains 2 list then
    Some list.[2]
  else
    None
)
Run Code Online (Sandbox Code Playgroud)

使用上面的解决方案,您只需遍历列表一次.


s95*_*163 5

我想你可以按照描述问题的方式去做:

p 
|> List.filter (List.contains 2) //first filter out lists with 2 in it
|> List.map (fun x -> x.[2]) //get the third element, this is the same as List.item 2 

//val it : int list = [1; 5; 10]
Run Code Online (Sandbox Code Playgroud)