Suppose that I have a list myList
that has more than one level. Here is an example of such a "data structure":
myList = {{10, "c"}, {20, "a"}, {30, "b"}};
Now suppose that I have a list of characters, called charList
:
charList = {"a", "b", "c"};
I want to use Position
to find the positions of the charList
characters in myList
. Of course, I can do this manually -- by calling Position
for each character in charList
:
Position[myList, _?(#[[2]] == "a" &), {1}, Heads -> False]
Position[myList, _?(#[[2]] == "b" &), {1}, Heads -> False]
Position[myList, _?(#[[2]] == "c" &), {1}, Heads -> False]
{{2}}
{{3}}
{{1}}
And, of course, I can shorten this process by using Table
to call Position
repeatedly:
Table[
Position[myList, _?(#[[2]] == charList[[i]] &), {1}, Heads -> False],
{i, 1, Length[charList]}]
{{{2}}, {{3}}, {{1}}}
But, is it possible to shorten the code even more by using Map
? (I often find Map
more convenient and easier to read than Table
.) My initial thought was to do something like this:
Map[
Position[myList, _?(#[[2]] == # &), {1}, Heads -> False] &,
charList]
but I get undesired output:
{{}, {}, {}}
I think that I have failed to distinguish between the two different #
slots, which refer to two different things (they refer to different &
s). How can I distinguish the two #
so that I can Map
Position
across charList
?
Table
it can be quite neaterTable[Position[myList, {_, i,___}, {1}, Heads -> False], {i, charList}]
$\endgroup$Map[Function[x, Position[myList, _?(#[[2]] == x &), {1}, Heads -> False]], charList]
$\endgroup$