Search code examples
pythonlist

Is there a better method to replace values in a Python list?


I am downloading aurora forecast data from the NOAA SWPC. The data is available as JSON and part of it is a list of lists (?) containing lon, lat and value like this:

[
   [0,-90,4],
   [0,-89,0],
   ...
]

The problem is that the longitude in the file goes from 0 to 360 instead of -180 to 180. To address this, I run a loop over the list:

import requests

r = requests.get("https://services.swpc.noaa.gov/json/ovation_aurora_latest.json")
data = r.json()
coords = data['coordinates']
for e in coords:
    if (e[0] > 180):
        e[0] -= 360

Is there a "better" / more "elegant" / more "pythony" way to do this?


Solution

  • You could use list comprehensions:

    import requests
    
    r = requests.get("https://services.swpc.noaa.gov/json/ovation_aurora_latest.json")
    data = r.json()
    
    coords = [[(lo - 360 if lo > 180 else lo), lat, x] for lo, lat, x in data['coordinates']]