Complicated list slicing
list = {{1, {x1, y1, z1}}, {2, {x2, y2, z2}}, {3, {x3, y3, z3}}};
In addition to your current method
{#[[1]], #[[2, 2]]} & /@ list
You can use a number of additional methods, including
Transpose[{list[[All, 1]], list[[All, 2, 2]]}]
{#, #2[[2]]} & @@@ list
{#, #2 & @@ #2} & @@@ list
Transpose@Extract[Transpose[list], {{1}, {2, All, 2}}]
list2 = list; list2[[All, 2]] = list2[[All, 2, 2]]; list2
(* or, more simply, list[[All,2]]=list[[All,2,2]] if you want to modify the list *)
list3 = list; list3[[All, 2, 0]] = #2 &; list3
to get
{{1, y1}, {2, y2}, {3, y3}}
I find extracting the parts and then combining them (e.g. with Transpose
) to be fast and general. kguler already showed this but again for reference:
{list[[All, 1]], list[[All, 2, 2]]}\[Transpose]
{{1, y1}, {2, y2}, {3, y3}}
Pattern matching is another general method, though often not quite as fast.
Cases[list, {a_, b_} :> {a, b[[2]]}]
{{1, y1}, {2, y2}, {3, y3}}
Since your example only requires modification of the {x1, y1, z1}
part you could also use MapAt
:
MapAt[#[[2]] &, list, {All, 2}]
{{1, y1}, {2, y2}, {3, y3}}
Using Replace
list /. {a_, b_List} :> {a, b[[2]]}
or
Replace[list, a_List :> a[[2]], {2}]
{{1, y1}, {2, y2}, {3, y3}}