I have the following code
avg_lat={}
g_coords={}
for year,lat,num,long in zip(years,latitudes,quantities,longitudes):
if year in avg_lat:
avg_lat[year] = lat #Ignore avg_lat, this bit is irrelevant, but I gotta keep it for the code to work
if 58.50>lat>56.83 and 17.83>long>15.26:
g_coords[year] =num
else:
avg_lat[year] = lat
g_coords[year]=num
return g_coords
Now my problem is that it's obviously making keys that aren't fullfiling the requirement, how can I change the code so that it only registers keys when it fulfills the requirment and then for nonunique keys add the values together? Note that I'm not allowed to use pandas either, only numpy
Edit: Here are some examples of what the arrays can look like and what I expect the result to be:
return years,,latitudes,quantites,longitudes
output:
(array([2021, 2021, 2021, ..., 1996, 1996, 1996]), array([59.0193253, 59.4408419, 59.2559116, ..., 55.5246801, 55.5234546,
56.1633051]), array([1, 1, 1, ..., 2, 6, 1]), array([17.619529 , 18.6676653, 18.2598482, ..., 12.9141087, 12.9079911,
14.903895 ]))
The requirement is
if 58.50>lat>56.83 and 17.83>long>15.26: g_coords[year] =num
. So in essence I want it to store the amount of observations of the year that are in a certain place.
latitudes=[58.60,57.0,55.9]
longitudes=[17.69,16.0,15.5]
quantites=[2,3,6]
print(g_coords)
output: (2021:5)```
CodePudding user response:
You can use a defaultdict from the standar library:
from collections import defaultdict
# outside of the loop
g_coords = defaultdict(int)
# inside the loop
g_coords['some_key'] =1
This way you don't have to initialize the keys and don't have to insert values with zeros, or num as you have stated in your code.
CodePudding user response:
I'm not sure what you need avg_lat
for. But strictly addressing the question you ask in your post, you can do:
g_coords={}
for year,lat,num,long in zip(years,latitudes,quantities,longitudes):
if 58.50>lat>56.83 and 17.83>long>15.26:
if year not in g_coords:
g_coords[year] = 0 #initialize with 0 if the key doesn't exist
g_coords[year] = num