3
$\begingroup$

Suppose I have a list of the following:

list={{1,2},{1,6.5},{1,6},{1,0}....{1,36}}.

Let say the Length of the list is 300. I would like to sum the first member of the first case of the list by 0. The first member of the second case by 1. The first member of the third case by 2 and so on. The result would be the following:

{{1,2},{2,6.5},{3,6},{4,0},...{300,36}}
$\endgroup$

4 Answers 4

1
$\begingroup$
list = {{1, 2}, {1, 6.5}, {1, 6}, {1, 0}, {1, 36}};

add = Transpose[{Range@# - 1, Array[0 &, #]}] &[Length@list]

{{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}}

list + add

{{1, 2}, {2, 6.5}, {3, 6}, {4, 0}, {5, 36}}

Or

ReplacePart[list, i_ :> {list[[i, 1]] + i - 1, list[[i, 2]]}]

{{1, 2}, {2, 6.5}, {3, 6}, {4, 0}, {5, 36}}

$\endgroup$
1
  • $\begingroup$ Perfect! Thanks! $\endgroup$
    – fermi
    Dec 11, 2015 at 21:56
3
$\begingroup$
MapIndexed[{First@#2 - 1, 0} + #1 &, list]
$\endgroup$
1
  • 1
    $\begingroup$ MapIndexed[#1 + Append[#2 - 1, 0] &, list] is also a possibility. $\endgroup$ Dec 12, 2015 at 1:20
3
$\begingroup$
list[[All, 1]] = list[[All, 1]] + Range[0, Length[list] - 1];
list
$\endgroup$
3
$\begingroup$

MapAt, which seems to often slip under the radar on this site, can be used to solve this problem.

data = {{1, 2}, {1, 6.5}, {1, 6}, {1, 0}, {1, 36}};
Transpose[MapAt[Accumulate, Transpose[data], 1]]

{{1, 2}, {2, 6.5}, {3, 6}, {4, 0}, {5, 36}}

$\endgroup$
1
  • $\begingroup$ +1 for using Accumulate, because that helped me solve a similar problem: I wanted to accumulate the second element of each tuple in a list of pairs. Or, even accumulate a list, then combine the list with another list to create the pairs since I know how to do that.... So thanks for exposing this part of the API, Accumulate, to us on SE. $\endgroup$ Jun 13, 2017 at 21:57

Your Answer

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

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