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

Python如何将标准输入(stdin)转换为指定格式的list数据结构

Python实现标准输入转嵌套列表方案

处理逻辑

  • 逐行读取标准输入,跳过空行后将每行内容转换为整数列表
  • 遇到值不为0的单个整数时,作为新子列表的起始元素:若此前存在未完成的子列表,先将其加入结果列表,再初始化新的当前子列表
  • 遇到包含两个整数的行时,直接将该行对应的列表加入当前正在构建的子列表
  • 遇到值为0的单个整数时,将其加入当前子列表末尾,再将该子列表加入结果列表,结束处理

实现代码

import sys

result = []
current_group = None

for line in sys.stdin:
    stripped_line = line.strip()
    # 跳过空行
    if not stripped_line:
        continue
    nums = list(map(int, stripped_line.split()))
    # 处理单行单个数字的情况
    if len(nums) == 1:
        num = nums[0]
        if num == 0:
            # 遇到终止符0,加入当前组后结束处理
            if current_group is not None:
                # 如果需要0以[0]列表形式存储,替换为current_group.append([num])
                current_group.append(num)
                result.append(current_group)
            break
        else:
            # 新子组开始,先保存上一个未完成的子组
            if current_group is not None:
                result.append(current_group)
            current_group = [num]
    # 处理单行两个数字的情况
    elif len(nums) == 2:
        if current_group is not None:
            current_group.append(nums)

# 输出最终结果
print(result)

输出调整说明

如果你需要最终结果里的0以列表[0]形式存储,和示例输出完全匹配,只需将代码中current_group.append(num)修改为current_group.append([num])即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:54:04