1
$\begingroup$

I've declared a list:

list = {{1, 2}, {2}, {3, 4, 1}, {5, 4}, {3, 3}, {a, b, c}, {e, 
    f}, {g}, {}, {Sin[a], Cos[b]}};

now I've made an rule which add 2 pairs together:

Cases[list, {x_, y_} -> x + y] 

later only Integer numbers:

Cases[list, {x_Integer, y_Integer} -> x + y]

But now i want find the sum of sublists which have the Length >=2 so that the result is:

{3,8,9,6,a+b+c,e+f,Cos[b]+Sin[a]}

and after that I want to find the sum of all sublists so that the result would be:

{3,2,8,9,6,a+b+c,e+f,g,0,Cos[b]+Sin[a]}

Thanks for helping

$\endgroup$
19
  • $\begingroup$ Cases[list, {x_Integer, y_Integer} -> x + y] $\endgroup$
    – MarcoB
    May 9, 2016 at 19:52
  • $\begingroup$ the length shouldn't be lower than >=3 $\endgroup$
    – Katze
    May 9, 2016 at 19:55
  • 1
    $\begingroup$ list /. {x_Integer, y_Integer} -> {x + y} returns {{8}, {2}, {2, 6, 7}, {5}, {2.5, 3.2}}. However, I am not sure that this is what you want. You really should include your desired result in the question. $\endgroup$
    – MarcoB
    May 9, 2016 at 20:03
  • $\begingroup$ Yes that is the result what i want. But now i want to do this Cases[list, {x_Integer, y_Integer} -> x + y,Length>=3] so that only the lists which are higher and equal 3 as a sum in a result $\endgroup$
    – Katze
    May 9, 2016 at 20:05
  • 1
    $\begingroup$ @Katze. Maybe Select[newlist, Total[{Sequence @@ #}] == 7 &] where newlist = {{1, 2, 4}, 6, 7, 8, {8, 2}, {3, 4}, {4, 5}, {1, 2, 3, 1}};. Output is {{1, 2, 4}, 7, {3, 4}, {1, 2, 3, 1}}. Stephen Wolfram's book, An Elementary Introduction to the Wolfram Language, which you are probably aware of, explains things much better than I can. $\endgroup$
    – user1066
    May 10, 2016 at 0:18

2 Answers 2

3
$\begingroup$

You may use Total and Select.

Total /@ Select[Length@# >= 2 &]@list

{3, 8, 9, 6, a + b + c, e + f, Cos[b] + Sin[a]}

Total /@ list

{3, 2, 8, 9, 6, a + b + c, e + f, g, 0, Cos[b] + Sin[a]}

Hope this helps.

$\endgroup$
2
  • 2
    $\begingroup$ Instead of mapping: Total[Select[list, Length[#] >= 2 &], {2}]. $\endgroup$ May 10, 2016 at 9:06
  • $\begingroup$ @J.M. Nice addition. +1 $\endgroup$
    – Edmund
    May 10, 2016 at 9:14
2
$\begingroup$

Since you insist on using Cases:

list = {{1, 2}, {2}, {3, 4, 1}, {5, 4}, {3, 3}, {a, b, c}, 
   {e,f}, {g}, {}, {Sin[a], Cos[b]}};

Cases[list, sub : {_, __} :> Total@sub]
 {3, 8, 9, 6, a + b + c, e + f, Cos[b] + Sin[a]}
$\endgroup$
2
  • 1
    $\begingroup$ Or, as I said in a comment, Cases[list, {x_, y__} :> x + y] $\endgroup$
    – user1066
    May 10, 2016 at 9:53
  • $\begingroup$ @TomD Sorry, missed that comment, just read first two and last two of them :/ $\endgroup$
    – Kuba
    May 10, 2016 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.