如何在Node.js中统计CSV列内白球与红球数字的出现次数?
问题描述
现有如下结构的CSV文件:
Draw Date,Winning Numbers,Multiplier 10/15/2022,32 37 40 58 62 15,5 10/12/2022,14 30 41 42 59 06,5 10/10/2022,03 06 11 17 22 11,2 10/08/2022,13 43 53 60 68 05,2
需要生成两个统计表格:
- 白球数字(Winning Numbers列前5个,范围1-69)的出现次数统计
- 红球数字(Winning Numbers列第6个,范围1-26)的出现次数统计
已完成CSV文件的读写配置,但无法实现指定列的分段统计及数字计数跟踪。
解决方案
以下是基于Python的实现代码,可直接整合进现有CSV读写逻辑:
import csv from collections import defaultdict # 初始化计数器:覆盖所有目标数字,初始计数为0 whiteball_counts = defaultdict(int) for num in range(1, 70): whiteball_counts[num] = 0 redball_counts = defaultdict(int) for num in range(1, 27): redball_counts[num] = 0 # 读取CSV文件(替换为你的实际文件名) with open('lottery.csv', 'r', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: # 拆分数字并处理前导零,转为整数 numbers = [int(num.lstrip('0')) for num in row['Winning Numbers'].split()] # 分离白球(前5个)和红球(第6个) whiteballs = numbers[:5] redball = numbers[5] # 更新计数 for num in whiteballs: whiteball_counts[num] += 1 redball_counts[redball] += 1 # 输出白球统计表格 print("Whiteball Numbers | Times Drawn") for num in sorted(whiteball_counts.keys()): print(f"{num}: {whiteball_counts[num]}") # 输出红球统计表格 print("\nRed Ball Number | Times Drawn") for num in sorted(redball_counts.keys()): print(f"{num}: {redball_counts[num]}")
关键逻辑说明
- 计数器初始化:提前创建包含所有目标数字的字典,确保未出现的数字也能显示0次,避免遗漏。
- 数字格式化:去除数字前的前导零(如
03转为3),保证计数的准确性。 - 分段统计:通过列表切片分离白球和红球,分别更新对应计数器。
- 有序输出:按数字升序打印结果,符合要求的表格格式。
内容的提问来源于stack exchange,提问作者Alexandra M.
相关产品推荐
相关产品推荐

