您可以使用以下代码示例来解决这个问题:
def get_popular_spelling(arr, property):
spelling_count = {} # 用于记录每个拼写的出现次数
total_sum = 0 # 所有拼写的总和
# 遍历数组中的每个对象
for obj in arr:
spelling = obj[property] # 获取对象的属性值
# 如果拼写已经在字典中,则增加其计数器
if spelling in spelling_count:
spelling_count[spelling] += 1
else:
spelling_count[spelling] = 1
# 增加总和
total_sum += spelling
# 按降序对字典中的拼写计数进行排序
sorted_spelling_count = sorted(spelling_count.items(), key=lambda x: x[1], reverse=True)
# 返回最流行的拼写和总和
return sorted_spelling_count[0][0], total_sum
使用示例:
arr = [
{'name': 'John', 'spelling': 'John'},
{'name': 'Amy', 'spelling': 'Amy'},
{'name': 'John', 'spelling': 'John'},
{'name': 'Amy', 'spelling': 'Aimee'},
{'name': 'John', 'spelling': 'Jon'},
{'name': 'Amy', 'spelling': 'Amie'},
]
popular_spelling, total_sum = get_popular_spelling(arr, 'spelling')
print("Most popular spelling:", popular_spelling)
print("Total sum of spellings:", total_sum)
输出结果:
Most popular spelling: John
Total sum of spellings: 11
在上面的示例中,我们使用一个字典spelling_count
来记录每个拼写的出现次数。然后,我们使用sorted()
函数按降序对字典的拼写计数进行排序。最后,我们返回最流行的拼写和所有拼写的总和。
上一篇:按降序返回结果
下一篇:按降序获取具有多个子节点的父节点