【问题标题】:How to convert input stdin to list data structure in python [closed]如何在python中将输入标准输入转换为列表数据结构[关闭]
【发布时间】:2021-09-10 16:47:41
【问题描述】:

我有一个这种格式的标准输入数据:
100
85 92
292 42
88 33
500
350 36
800 45
0

我想要这样的东西 [[100, [85, 92], [292, 42], [88, 33]], [500, [350, 36], [800, 45], [0]]

【问题讨论】:

  • 为什么 100 和 500 不在列表中,而 0 在列表中?
  • 你卡在哪里了?例如,for line in sys.stdin: 是如何从标准输入流中读取行。
  • 首先将您的标准输入数据格式转换/更改为数组并尝试自己,如果您遇到困难,请分享您的努力并寻求解决方案

标签: arrays python-3.x stdin


【解决方案1】:

类似以下的东西(我已经测试过)应该这样做:

lst = []
sublst = []
for line in sys.stdin:
    lineLst = [int(x) for x in line.split()]
    if len(lineLst) == 1:
        if sublst: lst.append(sublst)
        sublst = lineLst
    else:
        sublst.append(lineLst)
    
if sublst[0] == 0: lst.append(sublst)

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2020-06-13
    相关资源
    最近更新 更多