You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用for循环读取输入数字并计算配对数值之和方法咨询

实现方案

你现有代码仅在循环中逐次读取数字但未做存储,无法完成配对计算,下面提供两种可直接运行的实现方式:

方式1:先存储所有数字再配对计算

适合需要保留所有输入数字后续做其他处理的场景:

count_of_pairs = int(input())
num_list = []

# 读取指定数量的输入数字存入列表
for _ in range(2 * count_of_pairs):
    num_list.append(int(input()))

# 步长为2遍历列表,两两求和输出
for idx in range(0, len(num_list), 2):
    sum_res = num_list[idx] + num_list[idx + 1]
    print(f"{num_list[idx]}+{num_list[idx+1]}={sum_res}")

方式2:逐对读取直接输出

不需要额外存储所有数字,内存占用更低:

count_of_pairs = int(input())

# 每轮循环读取两个数字直接计算输出
for _ in range(count_of_pairs):
    num1 = int(input())
    num2 = int(input())
    print(f"{num1}+{num2}={num1 + num2}")

运行示例

以你给出的输入序列3、2、1、4、5、0、4为例,第一个输入的3代表要计算3组配对和,后续6个数字为待计算的数值,两种方式的输出结果均为:

2+1=3
4+5=9
0+4=4

内容的提问来源于stack exchange,提问作者Vexarez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:15:04