7

For example, consider the list defined below.

samplelist = {{{1,2,3,4}}, {{5,6,7,8}}};

How would I apply the Times operator to the subsets {1,2,3,4} and {5,6,7,8}?

Neither Map nor Apply work (or at least not in the ways I've tried).

If somebody could please help me out, I'd greatly appreciate it. I seem to run into this problem of trying to circumvent extra curly brackets quite often.

Edit: Sorry for not clarifying. The desired output is {24,1680}. Extra brackets are fine for something like {{24},{1680}} since at this point, Flatten can be used.

Karsten7
  • 27,448
  • 5
  • 73
  • 134
user155812
  • 505
  • 3
  • 8

5 Answers5

11

I suspect you'd be fine with

samplelist /. {x__Integer} :> Times@x // Flatten

If you always store numbers you want to multiply in lists, and you know them to be integers, this will “apply” Times to all such lists in your data.

For more general numbers try something like

samplelist /. {x__?NumberQ} :> Times@x // Flatten

Note: this way you don't have to adjust Apply's (positive) levelspec to every single data sample you're dealing with, which is handy if you don't know in advance what depth exactly your lists will have, and if you also have lists of atoms you don't want to multiply. In absence of the latter condition, Mr Wizard's answer is probably better.

akater
  • 1,540
  • 11
  • 16
8

If elements are atomic you can use levelspec {-2}:

Apply[Times, samplelist, {-2}]
{{24}, {1680}}

Since Plus[x] and Times[x] each reduce to x you can also use -2 if you not want the extra brackets, as shown by ciao (rasher):

Apply[Times, samplelist, -2]
{24, 1680}

With a dummy head foo to see how this works:

Apply[foo, samplelist, -2]
{foo[foo[1, 2, 3, 4]], foo[foo[5, 6, 7, 8]]}

Some reading for you:

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
3

Another approach, perhaps only slightly different than @Akater's:

samplelist /. v_?VectorQ :> Times @@ v
(*  {{24}, {1680}}  *)

One can give VectorQ other arguments that restrict what type of elements the vector v might contain. By default, an element can be anything except a list.

For example:

{{{x, Exp[x], 3, 4, x Exp[x]}},
 {{{5, Plot[Sin[x], {x, 0, 2 Pi}], Plot[Sin[x], {x, 0, 2 Pi}]}}}} /.
  v_?VectorQ :> Times @@ v

Mathematica graphics

Michael E2
  • 235,386
  • 17
  • 334
  • 747
1

Some more options:

New in 12.2

ArrayReduce[Apply @ Times, list, 3]

{{24}, {1680}}

New in 13.1

ReplaceAt[list, x_ :> Times @@ x, {;; , ;;}]

{{24}, {1680}}

Query[;; , ;; , Apply @ Times] @ list

{{24}, {1680}}

eldo
  • 67,911
  • 5
  • 60
  • 168
1
Times @@@ samplelist ~Flatten~ 1

{24, 1680}

One could also directly Replace the innermost List with Times

Replace[samplelist, List -> Times, {3}, Heads -> True] // Flatten

{24, 1680}

Karsten7
  • 27,448
  • 5
  • 73
  • 134