Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 749
Jarod Avatar asked Oct 15 '25 04:10

Jarod


1 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]]
like image 195
wim Avatar answered Oct 16 '25 16:10

wim