开发者

Access & Select specific sub-list elements with a Pure Function

  • Part I : ACCESS

Provided with :

list = {{z, x, c, d}, {1, 2, 3, 4}}

I would like to do the following :

(#3/2 + #1/3) &[list[[1]]]

Which sadly result in :

Access & Select specific sub-list elements  with a Pure Function

While my desired output would be :

Access & Select specific sub-list elements  with a Pure Function

obtained with :

 (#3/2 + #1/3) &[z, x, c, d]
  • Part II : CONDITIONAL SELECTION

Trying to do this :

Select[list[[2]], # > 2 &] 

How could I specify the sublist with # if possible ?

Answer, courtesy of Leonid (detailed in a comment below) :开发者_运维问答

Select[#[[2]], # > 2 &] &[list]


You were almost there:

(#[[3]]/2 + #[[1]]/3) &[list[[1]]]

#1 is the first argument of a function and #3 is the third. You only provide one argument, namely list[[1]]. Since list[[1]] is a list it is mapped over your function. #[[1]] and #[[3]] specify the first and third part/element of the first argument.


You can use Sequence: (#3/2 + #1/3) &[Sequence @@ (list[[1]])] does what you want. Sequence can be very useful


Sometimes you may find useful to use some notation to improve readability. For example, elaborating on Markus' answer:

list = {{z, x, c, d}, {1, 2, 3, 4}}
third[x_List] := x[[3]];

third@#/2 + First@#/3 &@ First@list
(*
-> c/2+z/3
*)


For the first, you just need Apply (short form @@):

#3/2 + #1/3 & @@ list[[1]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜