Is there a built in method to de-list singleton expressions, like this rule-based solution:
expr_ :> If[Length[expr] == 1, First@expr, expr]
In data analysis, this comes in handy to normalize the output of Cases
, since a single exact match will be wrapped in a list, but wrapping that in First
would break no-match cases and non-singleton lists.
Answer
You can use a simple replacement rule like in the following example:
list = {a, {b}, {c, d}, {e, {f, g}}, {{h}}};
list /. _[x_] :> x
(* {a, b, {c, d}, {e, {f, g}}, {h}} *)
This will strip a layer from expressions with length 1, for all heads. You can restrict it further to act only on List
, if that's what you desire.
Comments
Post a Comment