Python读取含分组数字的文本文件,求分组求和前三值之和问题
解决方案
1. 读取文件并计算每组数字的和
先遍历文件内容,按空行分割分组,计算每组的总和并存入列表:
group_sums = [] current_sum = 0 with open('你的文件名.txt', 'r') as f: for line in f: line = line.strip() if line: # 非空行,累加数字 current_sum += int(line) else: # 遇到空行,保存当前组的和并重置计数器 group_sums.append(current_sum) current_sum = 0 # 处理文件末尾没有空行的最后一组 if current_sum != 0: group_sums.append(current_sum)
2. 获取前三最大的和并相加
这里提供两种实用方法:
方法一:排序取前三(简洁直观)
把所有组的和降序排序,直接取前三个相加:
# 降序排序 sorted_sums = sorted(group_sums, reverse=True) # 计算前三最大值的总和 top_three_total = sum(sorted_sums[:3]) print(top_three_total)
方法二:遍历维护前三值(适合超大文件)
如果文件数据量极大,排序会占用过多内存,用这种方式更高效:
first = second = third = 0 for s in group_sums: if s > first: third = second second = first first = s elif s > second: third = second second = s elif s > third: third = s top_three_total = first + second + third print(top_three_total)
完整代码示例
把两部分整合,直接可用:
group_sums = [] current_sum = 0 # 读取文件计算每组和 with open('你的文件名.txt', 'r') as f: for line in f: stripped_line = line.strip() if stripped_line: current_sum += int(stripped_line) else: group_sums.append(current_sum) current_sum = 0 if current_sum != 0: group_sums.append(current_sum) # 排序法计算前三总和(注释掉可换方法二) sorted_sums = sorted(group_sums, reverse=True) print(sum(sorted_sums[:3]))
内容的提问来源于stack exchange,提问作者Dan Minto
相关产品推荐
相关产品推荐

