我想通过使用一些自定义质心计算函数向loc1
和loc2
字典添加一个名为"centroid"
的额外键。location_list
是字典loc1
和loc2
的列表
location_list = [loc1,loc2]
loc1 = {
"x_cor" : 10,
"y_cor" : 20}
loc2 = {
"x_cor" : 10,
"y_cor" : 25}
我想获得这两个位置的质心,并添加一个额外的键质心;到loc1和loc2。
质心计算函数如下:
def get_centroid(self, locations: list):
x, y = [p[0] for p in locations], [p[1] for p in locations]
centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
return centroid
预期输出:
loc1 = {
"x_cor" : 10,
"y_cor" : 20,
"centroid": (6.667 , 15)}
loc2 = {
"x_cor" : 10,
"y_cor" : 25,
"centroid": (6.667 , 15)}
是否有一种方法,我可以使用这个函数来添加一个额外的键"质心"这些字典?
def get_centroid(self, locations: list):
x, y = [p[0] for p in locations], [p[1] for p in locations]
centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
for location in locations:
location['centroid'] = centroid
return centroid
您的get_centroid
函数不起作用。由于字典是无序的,因此不能使用索引访问字典项,请将索引放入字典。
这意味着你必须将p[0]
替换为p['x_cor']
,将p[1]
替换为p['y_cor']
。
我不认为你需要self
作为get_centroid
的参数。self
不在函数代码中使用,它们主要在类中使用。
要为loc1
和loc2
添加质心,可以使用for循环。
for loc in locations:
loc['centroid'] = centroid
return locations
将此组合到您的get_centroid
函数中得到:
def get_centroid(locations: list):
x, y = [p['x_cor'] for p in locations], [p['y_cor'] for p in locations]
centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
for loc in locations:
loc['centroid'] = centroid
return locations
使用你提供的x和y坐标值和质心方程,我无法达到你预期的输出。我为质心实现的输出是(10.0,22.5)。
整个代码
def get_centroid(locations: list):
x, y = [p['x_cor'] for p in locations], [p['y_cor'] for p in locations]
centroid = [round(sum(x) / len(locations), 2), round(sum(y) / len(locations), 2)]
for loc in locations:
loc['centroid'] = centroid
return locations
loc1 = {
"x_cor" : 10,
"y_cor" : 20}
loc2 = {
"x_cor" : 10,
"y_cor" : 25}
location_list = [loc1,loc2]
print(get_centroid(location_list))
[{'x_cor': 10, 'y_cor': 20, 'centroid': [10.0, 22.5]}, {'x_cor': 10, 'y_cor': 25, 'centroid': [10.0, 22.5]}]