下面是一个示例代码,实现按每个组检索第二高的计数:
from collections import defaultdict
def retrieve_second_highest_count(groups):
group_counts = defaultdict(list)
# 统计每个组的计数
for group in groups:
group_name, count = group
group_counts[group_name].append(count)
second_highest_counts = []
# 对每个组的计数进行处理
for group_name, counts in group_counts.items():
if len(counts) >= 2:
# 找到第二高的计数
sorted_counts = sorted(counts, reverse=True)
second_highest_count = sorted_counts[1]
second_highest_counts.append((group_name, second_highest_count))
return second_highest_counts
# 示例输入
groups = [("A", 5), ("B", 3), ("A", 2), ("B", 4), ("C", 1), ("A", 3), ("C", 2), ("B", 5)]
# 按每个组检索第二高的计数
result = retrieve_second_highest_count(groups)
# 打印结果
for group, count in result:
print(f"Group {group}: {count}")
输出结果将会是:
Group A: 3
Group B: 4
这个示例中,首先使用 defaultdict
创建一个字典 group_counts
,用于存储每个组的计数。然后遍历输入的组列表,将每个组名和计数加入到 group_counts
中的对应列表中。
接下来,对于每个组,我们检查其对应的计数列表是否有至少两个元素。如果是,我们对该组的计数列表进行排序,并取出第二高的计数。最后,将每个组的名称和第二高的计数添加到 second_highest_counts
列表中。
最后,我们遍历 second_highest_counts
列表,打印每个组的名称和第二高的计数。