Getting indexes from Mathematica Select

How can I get select indices, not 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 the answer to the closest question (see below), but what about sorting. Say I want to sort a list, but instead of returning a sorted list, I want to return indexes in the order of a sorted list?

+4
source share
5 answers

WRT to the question left after your editing: 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
source

Ok, I figured out how to do this. Mathematica uses such a different dictionary that searching for documentation is still impractical for me (I searched 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 on templates in Mathematica.

+4
source

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} *) 
+2
source

Sorry, I quickly read your question.

I think your second question is how to sort the list according to the rule values. The easiest way that comes to mind is to use the comparison function. then just use your solution to extract indexes:

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

Hope this helps!

0
source

Without sorting or otherwise modifying the list, do the following:

 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 this to retrieve records from a database

 Lookup[list_, query_, column_: 1, resultColumns_: All] := list[[SelectIndex[list, StringMatchQ[query, #[[column]]] &], resultColumns]] Lookup(list,"foo") 
0
source

All Articles