Re: Sum elements in a list with conditions

*To*: mathgroup at smc.vnet.net*Subject*: [mg69842] Re: Sum elements in a list with conditions*From*: dimmechan at yahoo.com*Date*: Mon, 25 Sep 2006 03:53:02 -0400 (EDT)*References*: <ef5066$mm5$1@smc.vnet.net>

Your desired output can be achieved with proper pattern matching. lst = {{a1, b1}, {a2, b2}, {a2, b3}, {a2, b4}, {a3, b5}, {a3, b6}}; lst //. {a___, {x_, y_}, {x_, z_}, b___} -> {a, {x, y + z}, b} {{a1, b1}, {a2, b2 + b3 + b4}, {a3, b5 + b6}} Information["___"] ___ (three _ characters) or BlankNullSequence[ ] is a pattern object that can stand for any sequence of zero or more Mathematica expressions. ___h or BlankNullSequence[h] can stand for any sequence of expressions, all of which have head h. Attributes[BlankNullSequence] = {Protected} Information["//."] expr //. rules repeatedly performs replacements until expr no longer changes. Attributes[ReplaceRepeated] = {Protected} Options[ReplaceRepeated] = {MaxIterations -> 65536} For example myrule = {a___, {x_, y_}, {x_, z_}, b___} -> {a, {x, y + z}, b}; dat=Table[Random[Integer,{1,5}],{30},{2}] {{4,3},{4,5},{4,2},{5,4},{4,2},{5,2},{2,4},{5,1},{1,3},{4,4},{3,1},{3,5}, {5,4},{3,1},{3,4},{2,5},{2,5},{3,5},{4,4},{2,4},{4,3},{4,5},{5,3},{5,4}, {5,1},{1,4},{5,2},{1,3},{3,1},{4,1}} dat//.myrule {{4,10},{5,4},{4,2},{5,2},{2,4},{5,1},{1,3},{4,4},{3,6},{5,4},{3,5},{2,10}, {3,5},{4,4},{2,4},{4,8},{5,8},{1,4},{5,2},{1,3},{3,1},{4,1}} Regards Dimitris