# I want to extract a specific element from the list and add it

{p[0, 8] -> 0.538464, p[1, 7] -> 0.107693, p[1, 8] -> 0.161539, \
p[2, 6] -> 0.0323078, p[2, 7] -> 0.0484617, p[2, 8] -> 0.0538464, \
p[3, 5] -> 0.00969234, p[3, 6] -> 0.0145385, p[3, 7] -> 0.0161539, \
p[4, 4] -> 0.0029077, p[4, 5] -> 0.00436155, p[4, 6] -> 0.00484617, \
p[5, 3] -> 0.000872311, p[5, 4] -> 0.00130847, p[5, 5] -> 0.00145385, \
p[6, 2] -> 0.000261693, p[6, 3] -> 0.00039254, p[6, 4] -> 0.000436155, \
p[7, 1] -> 0.000078508, p[7, 2] -> 0.000117762, p[7, 3] -> 0.000130847,\
p[8, 0] -> 0.0000235524, p[8, 1] -> 0.0000353286, p[8, 2] \-> 0.000039254,
p[9, 0] -> 0.0000176643, p[9, 1] -> 0.0000117762, p[10, 0] -> 8.83215*10^-6}


I want to extract a specific element from the list and add it. For example,　I want to extract the element which becomes 8 by the element of p [i, j] and add it.

p[0, 8] + p[1, 7] + p[2, 6] + ... = answer


Please advise an efficient way, thank you.

## 3 Answers

First assign a name to your above list, e.g., run

rules = (*your list*);


Then generate the expression you want, using Table or Array

sum = Plus @@ Table[p[i, 8 - i], {i, 0, 8}]
sum = Array[p[#, 8 - #] &, 9, 0, Plus]

p[0, 8] + p[1, 7] + p[2, 6] + p[3, 5] + p[4, 4] + p[5, 3] + p[6, 2] + p[7, 1] + p[8, 0]


Finally, apply the rules to finish the value substitution via ReplaceAll (/.):

sum /. rules

0.692301

• Thank you for advice.It solved properly. – Kenta Kawai Jan 8 at 7:53
 list= (*your list*)

Total[Select[list, (#[[1, 1]] + #[[1, 2]]) == 8 &] [[All, 2]]]

(*0.692301*)

• Thank you for advice.It solved properly. – Kenta Kawai Jan 8 at 7:53
• You can even use KeySelect: Total @ KeySelect[list, Plus @@ # == 8 &] – Sjoerd Smit Jan 8 at 17:02

Consider GroupBy or Merge. Pick is less specific but still applicable.

rules = {p[0, 8] -> 0.538464, p[1, 7] -> 0.107693, p[1, 8] -> 0.161539,
p[2, 6] -> 0.0323078, p[2, 7] -> 0.0484617, p[2, 8] -> 0.0538464,
p[3, 5] -> 0.00969234, p[3, 6] -> 0.0145385, p[3, 7] -> 0.0161539,
p[4, 4] -> 0.0029077, p[4, 5] -> 0.00436155, p[4, 6] -> 0.00484617,
p[5, 3] -> 0.000872311, p[5, 4] -> 0.00130847, p[5, 5] -> 0.00145385,
p[6, 2] -> 0.000261693, p[6, 3] -> 0.00039254, p[6, 4] -> 0.000436155,
p[7, 1] -> 0.000078508, p[7, 2] -> 0.000117762, p[7, 3] -> 0.000130847,
p[8, 0] -> 0.0000235524, p[8, 1] -> 0.0000353286, p[8, 2] -> 0.000039254,
p[9, 0] -> 0.0000176643, p[9, 1] -> 0.0000117762, p[10, 0] -> 8.83215*10^-6};

GroupBy[rules, Total@*First -> Last, Tr][8]

Merge[Total@# -> #2 & @@@ rules, Tr][8]

Merge[Plus @@@ # & /@ rules, Tr][8]

Merge[rules /. p -> Plus, Tr][8]

Pick[Values@rules, Total /@ Keys@rules, 8] // Tr


All give

0.692301