4
votes

How can I get the indices of a selection rather than the values. I.e.

list={3->4, 5->2, 1->1, 5->8, 3->2};
Select[list, #[[1]]==5&]; (* returns {5->2, 5->8} *)

I would like something like

SelectIndices[list, #[[1]]==5&]; (* returns {2, 4} *)

EDIT: I found an answer to the immediate question above (see below), but what about sorting. Say I want to sort a list but rather than returning the sorted list, I want to return the indices in the order of the sorted list?

5

5 Answers

4
votes

WRT to the question remaining after your edit: How about Ordering?

In[26]:= Ordering[{c, x, b, z, h}]

Out[26]= {3, 1, 5, 2, 4}

In[28]:= {c, x, b, z, h}[[Ordering[{c, x, b, z, h}]]]

Out[28]= {b, c, h, x, z}

In[27]:= Sort[{c, x, b, z, h}]

Out[27]= {b, c, h, x, z}
4
votes

Ok, well, I figured out a way to do this. Mathematica uses such a different vocabulary that searching the documentation still is generally unfruitful for me (I had been searching for things like, "Element index from Mathematica Select", to no avail.)

Anyway, this seems to be the way to do this:

Position[list, 5->_];

I guess its time to read up on patterns in Mathematica.

2
votes

I think you want Ordering:

Sort[list, #[[1]] == 5 &]
Ordering[list, All, #[[1]] == 5 &]
(*
{5->2,5->8,3->2,1->1,3->4}
{2,4,5,3,1}
*)
0
votes

Sorry, I had read your question to fast.

I think your second question is about how to sort the list according to the values of the rules. The simplest way that come to mind is by using a compare function. then simply use your solution to retrieve the indices:

comp[_ -> x_, a_ -> y_] := x < y;
Position[Sort[list, comp], 5 -> _]

Hope this helps!

0
votes

Without sorting or otherwise altering the list, do this:

SelectIndex[list_, fn_] :=  Module[{x}, 
  x = Reap[For[i = 1, i < Length[list], i++, If[fn[list[[i]]], Sow[i], Null];]];
  If[x[[1]] == {}, {}, x[[2, 1]]]]


list={ {"foo",1}, {"bar",2}};
SelectIndex[list, StringMatchQ[ #[[1]], "foo*"] &]

You can use that to extract records from a database

Lookup[list_, query_, column_: 1, resultColumns_: All] :=  list[[SelectIndex[list, StringMatchQ[query, #[[column]]] &], resultColumns]]

Lookup(list,"foo")