Selecting an item from a list in math

I have a large list of rules in Mathematica, but I want to select an item that matches certain criteria. Although I tried to use the Select and Take commands, I was not able to get the desired result.

Example. Suppose I want to select an item from a list, where A-> 1.2.

list={{A->1,B->2.1,C->5.2},{A->1.1,B->2.6,C->5.5},{A->1.2,B->2.7,C->5.7},{A->1.3,B->2.9,C->6.1}};

The desired result will be {A-> 1.2, B-> 2.7, C> 5.7}

I know that you can select items from lists based on their value. But how to do it from the list of rules?

thank

EDIT: Apparently, cases do the trick:

Cases [list, {A-> # | A-> Rationalization [#], Rule [_, _] ..}] and /@{1.2}

It is also looking for numbers in a rational and irrational form, which was another problem.

+3
source share
5

" {A- > 1,2, B- > 2.7, C- > 5.7}" :)

Cases[N@mylist, {___, A -> 1.2, ___}] // Flatten

N, - 6/5 1.2.

+1

- Select

Select[mylist, MemberQ[#, A -> 1] &]

(* {{A → 1, B → 2.1, C → 5.2}} *)

;

Select[mylist, MemberQ[#, A -> 1.1 |  1.2] &]

Select[mylist, 
 MemberQ[#, A -> 1.1 |  1.2 | 1.3] && FreeQ[#, C -> 6.1] &]
+3

Alternative:

Select[list, A == 1.2 /. # &]

The advantage of this solution is that it uses Equalinstead MatchQ(or equivalent). 1.2 == 6/5gives True(comparison in a mathematical sense), and MatchQ[1.2, 6/5]gives False(structural comparison). Of course, you can always do MatchQ[1.2, x_ /; x == 6/5]to get around this.

In addition, this decision ignores the order of the rules in the lists.

+3
source

Or use Cases:

Cases[list, {A -> 1.2, ___}]

+2
source

Other:

Pick[#, A /. #, 1.2]& @ list
+2
source

All Articles