当前编写的问题的问题是函数无法知道键名pair1
,因为每个字典都不同。
您可以pair
为每个字典使用一致的键名:
p1 = {'pair': ([2, 3, 4], [5, 6, 7])}
p2 = {'pair': ([9, 10, 11], [12, 13, 14])}
p3 = {'pair': ([12, 20, 30], [17, 8, 30])}
def find_and_set_mean(a_dictionary):
a_dictionary['mean']=np.mean(a_dictionary['pair'])
find_and_set_mean(p1)
find_and_set_mean(p2)
find_and_set_mean(p3)
这使:
{'pair': ([2, 3, 4], [5, 6, 7]), 'mean': 4.5}
{'pair': ([9, 10, 11], [12, 13, 14]), 'mean': 11.5}
{'pair': ([12, 20, 30], [17, 8, 30]), 'mean': 19.5}
但更好的解决方案可能是将其组织为一个对象:
class PairObject(object):
def __init__(self, _part1, _part2):
self.part1 = _part1
self.part2 = _part2
def pair(self):
return (self.part1, self.part2)
def mean(self):
return np.mean((self.part1, self.part2))
# Then use it like this:
p1 = PairObject([2, 3, 4], [5, 6, 7])
p1.pair() # returns ([2, 3, 4], [5, 6, 7])
p1.mean() # returns 4.5