Home > other >  How to convert negative values to positive values before they are calculated in a generator expressi
How to convert negative values to positive values before they are calculated in a generator expressi

Time:12-08

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.

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

CodePudding user response:

Just use the abs function in your comprehension list:

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

CodePudding user response:

Have you tried something like:

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