2
$\begingroup$

I have a list consisting mixed strings and numbers:

lis = {{{"a",1,2," 34 "},{"b",5,6," cc "}},{{"d",7," ee"},{"f",9,"1"}}

I would like to produce two sublists res1 and res2 as follows:

res1 consists of the first element of each sublist:

res1 = {"a","b","d","f"}

res2 is either: 1) the last element of each sublist IF it consists only of string representations of numbers (no letters) and 2) if it doesn't, then the second element will be the element immediately preceding the last element in the sublist as follows:

res2 = {" 34 ",6,7,"1"}

Thanks for suggestions.

$\endgroup$

2 Answers 2

2
$\begingroup$
lis = {{{"a", 1, 2, " 34 "}, {"b", 5, 6, " cc "}}, {{"d", 7, 
    " ee"}, {"f", 9, "1"}}}

res1 = First /@ Flatten[#, 1] &@lis

{"a", "b", "d", "f"}

f[k_List] := 
 If[StringMatchQ[StringTrim@Last@k, NumberString], Last@k, 
  Last@Most@k]

Or simply use k[[-1]] and k[[-2]] above.

res2 = f /@ Flatten[#, 1] &@lis

{" 34 ", 6, 7, "1"}

$\endgroup$
2
$\begingroup$
lis = {{{"a", 1, 2, " 34 "}, {"b", 5, 6, " cc "}}, {{"d", 7, 
     " ee"}, {"f", 9, "1"}}};

res1 = Flatten[lis, 1][[All, 1]]

(* {"a", "b", "d", "f"} *)

res2 = If[NumberQ@ToExpression[#[[-1]]], #[[-1]], #[[-2]]] & /@ 
 Flatten[lis, 1]

(* {" 34 ", 6, 7, "1"} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.