How do I subtract from every second[i][1] element in a 2d array?

Question:

Here is my 2d array:

[['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]]

I have created a loop to attach each appropriate label to its corresponding value within this 2d array. At the end of the loop I would like to subtract every value by a different number.

For example: if I wanted to subtract the values by 5

[['P1', 22], ['P2', 39], ['P3', 60], ['P4', 46], ['P5', 26], ['P6', 13], ['P7', 28]]

How do I do this while the array has both a str type and int?

Asked By: Jarod

||

Answers:

This is a simple job for a list comprehension:

>>> L = [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]]
>>> [[s, n - 5] for s, n in L]
[['P1', 22], ['P2', 39], ['P3', 60], ['P4', 46], ['P5', 26], ['P6', 13], ['P7', 28]]

Note that using a comprehension creates a new list and the original data will remain unmodified. If you want to modify the original in-place, it will be preferable to use a for-loop instead:

>>> for sublist in L:
...     sublist[1] -= 5
... 
>>> L
[['P1', 22], ['P2', 39], ['P3', 60], ['P4', 46], ['P5', 26], ['P6', 13], ['P7', 28]]
Answered By: wim

As an example, this works:

Array1 = [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]]

Array2 = [[i[0],i[1]-5] for i in Array1]

print(Array2)

Well, this is just a slightly different phrasing for the other answer 🙂

Answered By: Swifty

You can do with map,

l = [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]]
result = list(map(lambda x:[x[0],x[1]-5], l))

Output:

[['P1', 22],
 ['P2', 39],
 ['P3', 60],
 ['P4', 46],
 ['P5', 26],
 ['P6', 13],
 ['P7', 28]]
Answered By: Rahul K P

For bigger lists, use numpy like this:

import numpy as np
data = [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]]
a = np.array(data, dtype=object)

a[:, 1] = a[:, 1] - 5

a:

array([['P1', 22],
       ['P2', 39],
       ['P3', 60],
       ['P4', 46],
       ['P5', 26],
       ['P6', 13],
       ['P7', 28]], dtype=object)
Answered By: bitflip
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.