我有以下代碼
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
現在我的問題是,它顯然正在制作不滿足要求的鍵,我該如何更改代碼,以便它僅在滿足要求時注冊鍵,然后對于非唯一鍵將值添加在一起?請注意,我也不允許使用熊貓,只有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)```
uj5u.com熱心網友回復:
您可以使用標準庫中的defaultdict:
from collections import defaultdict
# outside of the loop
g_coords = defaultdict(int)
# inside the loop
g_coords['some_key'] =1
這樣您就不必初始化鍵,也不必像代碼中所述那樣插入帶有零或 num 的值。
uj5u.com熱心網友回復:
我不確定你需要什么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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325909.html
上一篇:原始錯誤是:dlopen(/Users/ulto4/miniforge3/envs/python386/lib/python3.8/site-packages/numpy/core/_multiarr
