4
$\begingroup$

I have a list:

lis = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}};

...and I would like to make a new list consisting of all elements of lis that begin with "AB", to make:

res = {{"AB",2,3},{"ABC",8,9}}

This would seem to be a job for SequenceCases, but am not sure how to construct it.

$\endgroup$

3 Answers 3

6
$\begingroup$

I am sure there are many ways to do this. How about using Cases ?

lis = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}};
Cases[lis, x_ /; (Head[x] === List && StringStartsQ[First@x, "AB"])]

Mathematica graphics

$\endgroup$
4
$\begingroup$
Cases[{_String?(StringMatchQ["AB*"]), ___}] @ lis
{{"AB", 2, 3}, {"ABC", 8, 9}}
$\endgroup$
1
$\begingroup$

EDIT

lis = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}};

Select[ListQ@# && StringStartsQ[First@#, "AB"] &][#] &@lis

{{"AB", 2, 3}, {"ABC", 8, 9}}


ORIGINAL

As a test case, I have added an entry at the end:

lis = {1, {"AB", 2, 3}, {"ABC", 8, 9}, {"BC", 7}, {4, "CA"}};

Select lists: (Not necessary but for demo)

f = Cases[#, _List] &

Select lists with first String element (This takes care of the element being a list too)

g = Cases[#, {k_String, x___}] &

First element (which is String) matches a pattern:

h[x_List] := Pick[x, StringMatchQ[First@x, "AB" ~~ ___]]

Execute:

h /@ g @ f@ lis

OR:

Composition[Map[h, #] &, g, f][lis]

OR:

h /@ g @* f @ lis

{{"AB", 2, 3}, {"ABC", 8, 9}}

$\endgroup$
1
  • $\begingroup$ Select[ListQ@# && StringStartsQ[First@#, "AB"] &]@lis works, f[#]& @x vs f@x $\endgroup$ May 11 at 6:28

Your Answer

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

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