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 to convert negative values to positive values before they are calculated in a generator expression with a slice?

The format of my JSON is as follows:

[
  ...
  {'minute': 87, 'value': -100},
  {'minute': 88, 'value': 4},
  {'minute': 89, 'value': -85},
  {'minute': 90, 'value': 4},
  {'minute': 90.5, 'value': 15}
]

To calculate the last 5 values I use:

response2 = requests.get(url2, headers=headers).json()
graphs = response2['graphPoints']

    sum(d["value"] for d in graphs["graphPoints"][-5:])

But I would like to convert these negative values to positive before they are calculated.

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

How I could do this in a simple or fast way without having to work with a list such as list_of_values = [] and then create a looping for value in list_of_values: to convert each value?

The current result is -100+4-85+4+15 = -162

The expected result is 100+4+85+4+15 = 208

>Solution :

Just use the abs function in your comprehension list:

sum(abs(d["value"]) for d in graphs["graphPoints"][-5:])
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