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

Python如何实现多行输入?使用input()无法正常处理该如何解决

Python 按首行指定行数接收多行输入实现方案

基础实现逻辑

首先通过input()读取首行的总行数,转换为整数后循环对应次数,逐行读取后续输入内容即可。
示例代码如下,适配整数输入场景:

# 读取首行标注的总输入行数
line_count = int(input())
# 存储所有输入内容的列表
input_list = []
for _ in range(line_count):
    # 按需求转换输入类型,示例为转换为整数
    current_line = int(input())
    input_list.append(current_line)

简化写法

可以用列表推导式压缩代码:

line_count = int(input())
input_list = [int(input()) for _ in range(line_count)]

注意事项

  • 若首行输入存在首尾空格,可加strip()避免类型转换报错:line_count = int(input().strip())
  • 若不需要留存所有输入,仅需逐行处理,可直接在循环内编写逻辑,无需存储到列表:
line_count = int(input())
for _ in range(line_count):
    num = int(input())
    # 此处添加你的处理逻辑
    print(num * 2)

运行效果匹配

对应给出的输入样例:

3
12
504
17
运行代码后得到的input_list结果为 [12, 504, 17],完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:45:04