7
$\begingroup$

I have a list each element of which consists of a list containing two strings and two integers:

lis = {{"ab", 2, "c", 3}, {"d", 3, "e", 4}, {"ac", 5, "f", 6}, {"c", 7, "d", 8}, {"ad", 9, "c", 10}}

I would like to create a new list that includes every member of lis whose first element starts with "a":

res = {{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

This would seem to be a simple task for StringCases, but I am not having much luck; suggestions would be gratefully received.

$\endgroup$
9
$\begingroup$

Some options:

Pick[
 lis,
 StringStartsQ[lis[[All, 1]], "a"]
 ]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

Select[lis, StringStartsQ[First[#], "a"] &]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

Cases[lis, {_?(StringStartsQ["a"]), ___}]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

$\endgroup$
  • $\begingroup$ Thank you for the options, I'll check which is faster with a large data set I have. $\endgroup$ – Suite401 Sep 6 '19 at 4:53
  • $\begingroup$ :> m in Cases is not necessary. $\endgroup$ – Αλέξανδρος Ζεγγ Sep 6 '19 at 7:48
  • $\begingroup$ @ΑλέξανδροςΖεγγ Thanks. $\endgroup$ – C. E. Sep 6 '19 at 9:31
4
$\begingroup$

Alternate solutions using string patterns:

Pick[lis, StringMatchQ[lis[[All, 1]], "a" ~~ ___]]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

Pick[lis, StringCases[lis[[All, 1]], "a" ~~ ___] // Map[Length], 1]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

Pick[lis, StringPosition[lis[[All, 1]], "a" ~~ ___] // Map[MatrixQ]]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

$\endgroup$
4
$\begingroup$

A few additional variations:

Pick[lis, StringMatchQ["a*"]@lis[[All, 1]]]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

Pick[lis, StringTake[lis[[All, 1]], 1], "a"]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

Pick[lis, Order[#, "b"]& /@ lis[[All, 1]], 1]

{{"ab", 2, "c", 3}, {"ac", 5, "f", 6}, {"ad", 9, "c", 10}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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