仅在间隔内创建键并添加相同键的值

  • 本文关键字:添加 创建 python list numpy
  • 更新时间 :
  • 英文 :


我有以下代码

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

现在我的问题是,它显然是使键不满足要求,我怎么能改变代码,使它只注册键时,它满足要求,然后为非唯一键加值在一起?注意,我也不允许使用pandas,只能使用numpy

编辑:以下是数组的一些示例,以及我期望的结果:

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 ]))

要求是if 58.50>lat>56.83 and 17.83>long>15.26: g_coords[year]+=num。所以从本质上讲,我想让它存储在某个地方的一年的观测量。

latitudes=[58.60,57.0,55.9]
longitudes=[17.69,16.0,15.5]
quantites=[2,3,6]
print(g_coords)
output: (2021:5)```

我不确定你需要avg_lat做什么。但严格地解决你在帖子中提出的问题,你可以这样做:

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

您可以使用标准库中的默认字典:

from collections import defaultdict
# outside of the loop
g_coords = defaultdict(int)
# inside the loop
g_coords['some_key']+=1

这样,您就不必初始化键,也不必像您在代码中所述的那样插入带有0或num的值。