0

Sorry for the bad title..Didn't know how to describe this, feel free to change it to be more specific.

I have a list in this form:

list = {"a(0)", "a(1)", "a(2)"}

Now I want the positions of all a* in the list. At first I thought this is easily done with the Position-function, but then I had some difficulties:

Position[list, "a"]

Thought this would work, but somehow I'm missing something. So..how to implement the * to give me all a's regardless of the following characters?

holistic
  • 2,975
  • 15
  • 37

2 Answers2

2

If you really want to use Position :)...

Position[list, s_String?(! StringFreeQ[#, "a"] &)]
{{1}, {2}, {3}}
Kuba
  • 136,707
  • 13
  • 279
  • 740
  • This is nice and I get the correct results. But there is a warning message which I don't understand: StringFreeQ::strse: "String or list of strings expected at position 1 in !(StringFreeQ[List, "a"]). " – holistic Jul 10 '14 at 11:58
  • 1
    Try Position[list, s_String?(! StringFreeQ[#, "a"] &)]. – Kuba Jul 10 '14 at 12:02
  • works fine now! Can you explain why what the problem was maybe? Want to understand it :) – holistic Jul 10 '14 at 12:04
  • 1
    @holistic Position is scanning everything, Heads too, that's why we had to constrain the pattern. You could also do Position[list, s_?(! StringFreeQ[#, "a"] &), Heads->False] but the method with String is more safe in case of nonstrigs in the list. – Kuba Jul 10 '14 at 12:11
1
list = {"a(0)", "a(1)", "a(2)", "b(42)"}

You can get the elements that match like so:

els = Select[list, StringMatchQ[#, "a" ~~ ___] &]

(*
{"a(0)", "a(1)", "a(2)"}
*)

If you want their positions, you can map Position over this list:

Position[list, #] & /@ els

(*
{{{1}}, {{2}}, {{3}}}
*)
acl
  • 19,834
  • 3
  • 66
  • 91