Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['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?

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading