如何用Python3提取文本文件元素并跨文件搜索,实现迭代球员统计
Python实现Iteration分组球员统计
步骤1:读取超级球星名单到集合
先把superstarplayers.txt里的名字读进集合——集合的成员查询效率远高于列表,适合频繁做判断的场景:
# 读取超级球星名单,存入集合过滤空行 with open('superstarplayers.txt', 'r', encoding='utf-8') as f: superstars = {line.strip() for line in f if line.strip()}
- 用
with语句自动管理文件关闭,避免手动关文件的遗漏问题 strip()去掉每行的换行符和首尾空格,空行直接过滤掉
步骤2:遍历players.txt统计每组数据
players.txt的结构是「Iteration开头行 → 若干球员行 → 空白行」循环,我们逐行读取并跟踪当前组的统计数据:
# 处理players.txt,统计每组迭代的球员数和超级球星数 current_iter = None total_players = 0 superstar_count = 0 with open('players.txt', 'r', encoding='utf-8') as f: for line in f: line = line.strip() # 识别新的迭代组 if line.startswith('Iteration'): # 若不是第一组,先输出上一组的统计结果 if current_iter is not None: print(f"{current_iter}: 总球员数 {total_players}, 超级球星数 {superstar_count}") # 重置统计变量,切换到当前迭代组 current_iter = line total_players = 0 superstar_count = 0 # 处理非空的球员行 elif line: total_players += 1 if line in superstars: superstar_count += 1 # 输出最后一组的结果(最后一组后没有新的Iteration行触发输出) if current_iter is not None: print(f"{current_iter}: 总球员数 {total_players}, 超级球星数 {superstar_count}")
关键逻辑说明
- 分组切换触发:通过判断行是否以
Iteration开头来识别新组,自动输出上一组的统计数据 - 空白行处理:空白行直接跳过,不影响统计流程
- 高效查询:用集合存储超级球星名单,
line in superstars的查询时间复杂度为O(1),比列表的O(n)快很多 - 边界处理:单独处理最后一组的输出,避免因为文件末尾没有新的Iteration行导致数据遗漏
示例输入输出
假设players.txt内容:
Iteration 1
Messi
RonaldoIteration 2
Neymar
Mbappe
Hazard
superstarplayers.txt内容:
Messi
Ronaldo
Mbappe
运行代码后输出:
Iteration 1: 总球员数 2, 超级球星数 2 Iteration 2: 总球员数 3, 超级球星数 1
内容的提问来源于stack exchange,提问作者coffeeMonster
相关产品推荐
相关产品推荐

