Home > other >  I need to get the sum of each element from a list
I need to get the sum of each element from a list

Time:04-06

I have a list like that:

[[0 1 2] [4 6 9] ... [-1 0 3]]

and I need to get [3 19 ... 2], I mean sum of first element, second and .... n - element.

I´m gonna really appreciate your help.

Update: I tried with that:

to sum-first-item
  let out []
  ask turtles[
    let sum-elem sum map first data-train
    set out lput sum-elem out
  ]
end

CodePudding user response:

Each list's item (in your case: each inner list) can be accessed by using item (see here, but also know about first and last) or as the current element of foreach (see here).

Here a bunch of ways with which you can accomplish your goal. First showing simply how to operate on each inner list, then showing how to directly build a list containing each inner list's sum:

to play-with-lists
  print "The original list:"
  let list-of-lists [[0 1 2] [4 6 9] [-1 0 3]]
  print list-of-lists
  
  print "Manually reporting sums:"
  print sum item 0 list-of-lists
  print sum item 1 list-of-lists
  print sum item 2 list-of-lists
  
  print "Building a list of sums with while loop using 'while':"
  let list-of-sums []
  let i 0
  while [i < length list-of-lists] [
    set list-of-sums lput (sum item i list-of-lists) (list-of-sums)
    set i i   1
  ]
  print list-of-sums

  print "Building a list of sums with for loop using 'foreach':"
  set list-of-sums []
  foreach list-of-lists [
    inner-list ->
    set list-of-sums lput (sum inner-list) (list-of-sums)
  ]
  print list-of-sums
end
  • Related