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?
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With