1
$\begingroup$

I have a list as following:

l = {{"A", "b", "c", "d"}, {"A", "g", "x"}, {"b", "q", "r", 
"A"}, {"f", "t"}, {"A", "z"}}

I want to count the Length of those elements that they have "A". I have done as,

Map[Length, Table[Select[l[[i]], UpperCaseQ], {i, Length[l]}]]

this makes a table of those elements that have A and calculates the length, but what I am looking for is to have an outcome like: {4,3,4,2} namely there is A in element with Length 4, 3, 4 and 2. How shall I do this?

$\endgroup$

2 Answers 2

2
$\begingroup$
Length /@ Select[MemberQ["A"]] @ l

{4, 3, 4, 2}

To get lengths of sublists that contain an uppercase letter:

Length /@ Select[MemberQ[_?UpperCaseQ]] @ l 

{4, 3, 4, 2}

$\endgroup$
2
  • $\begingroup$ Thank you @kglr. Is it possible to make this general, the real list I have has some capital strings of different names think of it as "A", "B" and so on, so that's why I have used UpperCaseQ In other words, is there a way to do this without mentioning "A"? so it can scan all those entries that are capital? $\endgroup$
    – Wiliam
    Nov 5, 2018 at 12:14
  • 1
    $\begingroup$ @William, updated. $\endgroup$
    – kglr
    Nov 5, 2018 at 12:18
0
$\begingroup$

I think that (as always) @kglr has answered the question well. However to fully generalize the answer it seems like regular expressions might be useful. I found this surprisingly difficult. I convert OPs lists into strings, and then using Cases and StringMatchQ with the RegularExpression function. Seems clunky but allows for any sort of regex.

StringLength @ Cases[s_String /; StringMatchQ[s, 
    RegularExpression["([a-z]*[A-Z]+[a-z]*)"]]][StringJoin[#] & /@ l]

If I were coding with the idea that someone else might someday look at it, I might skip the one-liner and do:

regS = "([a-z]*[A-Z]+[a-z]*)";
sL = StringJoin[#] & /@ l;
sL = Cases[s_String /; StringMatchQ[s, RegularExpression[regS]]][sL];
StringLength @ sL

{4, 3, 4, 2}

$\endgroup$

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.