如何将终端多行空格分隔数字转为数组并计算数字2总数值
解决终端多行输入读取及数字统计问题
问题场景
终端输入为多行空格分隔的数字(示例如下),原代码使用input()仅能读取第一行,无法获取完整输入,最终需求是统计数字2的出现次数,并计算总数值(次数×2)。
示例输入:
4 3 2 1 3 4 2 2 3 3 2 1 2 3 4 4 1 3 2 1 4 2 4 1 1 1 4 3 4 4 4 1 2 2 3 4 2 1 1 2 1 1 1 3 2 2 2 3 2 3 3 4 3 2 4 1 1 3 3 2 2 2 4 4 3 2 1 4 4 3 2 1 4 3 2 2 2 4 3 1 2 3 1 1 4 1 3 4 2 4 3 3 2 4 2 2 1 1 1 1 4 3 4 1 3 3 2 2 1 1 3 1 4 2 1 1 3 3 1 2 3 2 2 1 2 3
原代码问题:input()仅读取单行输入,导致后续行数据丢失。
解决方案
1. 读取所有终端输入
要获取多行输入,有两种常用方式:
方法一:使用sys.stdin.read()一次性读取
需导入sys模块,直接读取所有输入内容并按行分割:
import sys # 读取全部输入内容,按换行分割为每行 full_input = sys.stdin.read() # 转换为二维整数数组,跳过空行 arr = [[int(num) for num in line.split()] for line in full_input.split('\n') if line.strip()]
方法二:循环读取直到EOF
无需导入模块,通过捕获EOFError判断输入结束:
arr = [] while True: try: line = input() if line.strip(): # 忽略空行 arr.append([int(num) for num in line.split()]) except EOFError: break
2. 统计数字2的次数及总数值
拿到完整数组后,可通过两种方式统计:
方式一:嵌套循环统计
count = 0 for row in arr: count += row.count(2) total_value = count * 2 print(f"数字2出现次数:{count},总数值:{total_value}")
方式二:扁平化数组后统计
用生成器表达式扁平化二维数组,再统计目标数字:
# 扁平化所有数字 all_numbers = (num for row in arr for num in row) # 统计2的次数 count = sum(1 for num in all_numbers if num == 2) total_value = count * 2 print(f"数字2出现次数:{count},总数值:{total_value}")
完整代码示例
整合读取与统计逻辑的完整代码(以sys.stdin版本为例):
import sys def calculate_two_stats(): # 读取全部输入 full_data = sys.stdin.read() # 转换为二维数组 num_matrix = [[int(num) for num in line.split()] for line in full_data.split('\n') if line.strip()] # 统计数字2的次数 two_count = sum(row.count(2) for row in num_matrix) total = two_count * 2 print(f"数字2出现{two_count}次,总数值为{total}") if __name__ == "__main__": calculate_two_stats()
内容的提问来源于stack exchange,提问作者Murilo Magalhães
相关产品推荐
相关产品推荐

