【问题标题】:Python - Parsing through multiple lines of data from STDIN to store in standard arrayPython - 解析来自 STDIN 的多行数据以存储在标准数组中
【发布时间】:2020-05-01 22:54:38
【问题描述】:

我已经完成了建议的类似问题,但似乎遇到了死胡同;可能是因为我可能没有充分解释我的问题。 我正在尝试获取一些我可以访问的 STDIN,如下所示:

0

80
90 29

20

我遇到的问题是将第一行之后的整数全部存储到标准 Python 数组中。

[80, 90, 29, 20]

第一行的第一个输入总是一些整数 0 或 1,表示禁用/启用某些“特殊功能”,然后输入任何其他整数,这些整数必须存储到标准数组中。正如你所看到的,一些整数有自己的行,而其他行可能有几个整数(应该完全忽略空白行)。 我一直在尝试使用 sys.stdin 来解决这个问题,因为我知道在剥离内容之后它已经将输入变成了列表对象,但是收效甚微。 到目前为止我的代码如下:

parse = True
arry = []
print('Special Feature?  (Give 0 to disable feature.)')
feature = input()
print('Please give the input data:')
while parse:
    line = sys.stdin.readline().rstrip('\n')
    if line == 'quit':
        parse = False
    else:
        arry.append(line)
print('INPUT DATA:', arry)

“退出”是我尝试使用可以手动输入的后门,因为我也不知道如何检查 EOF。我知道这是非常简单的(几乎没有什么),但我实际上希望生成的输出是这样的:

Special Feature?  (Give 0 to disable feature.)
> 0
Please give the input data:
> 80 90 29 20
INPUT DATA: [80, 90, 29, 20]

标有“>”的行没有打印出来,我只是在演示如何在概念上读取输入。 当然,感谢您的任何帮助,我期待您的想法!

【问题讨论】:

    标签: python arrays python-3.x stdin sys


    【解决方案1】:

    您可以遍历sys.stdin(阅读更多here)。

    为了存储您的数字,只需编写将从字符串中提取它们的任何代码,然后将数字附加到一个列表中。

    这是一个例子。

    import sys
    parse = True
    arry = []
    print('Special Feature?  (Give 0 to disable feature.)')
    feature = input()
    print('Please give the input data:')
    for l in sys.stdin:
        arry += l.strip().split() 
    print('INPUT DATA:', arry)
    

    创建一个新文件,例如data

    0
    1 2 3
    4 5 6
    

    现在尝试运行程序

    $ python3 f.py < data
    Special Feature?  (Give 0 to disable feature.)
    Please give the input data:
    INPUT DATA: ['1', '2', '3', '4', '5', '6']
    

    从文件中读取每个数字。

    【讨论】:

    • 抱歉,我没有提到我想用实际的整数而不是它们的字符串表示来打印“输入数据:”。但是,转换起来并不麻烦,所以这个答案非常适合我的需要。感谢您的帮助!
    【解决方案2】:

    如果你真的想保留sys.stdin(尽管input()),你可以使用这种方法:

    import sys
    
    parse = True
    arry = []
    print('Special Feature?  (Give 0 to disable feature.)')
    feature = input()
    print('Please give the input data:')
    while parse:
        line = sys.stdin.readline().rstrip('\n')
        if line == 'quit':
            parse = False
        elif line !='':
            arry += [int(x) for x in line.split()]
    print('INPUT DATA:', arry)
    

    输入:

    Special Feature?  (Give 0 to disable feature.)
    1
    Please give the input data:
    10
    
    20
    
    22
    
    
    1 3 5 0
    
    quit
    

    输出(输入数字转换为整数):

    INPUT DATA: [10, 20, 22, 1, 3, 5, 0]
    

    【讨论】:

    • 这太棒了;另一位用户指出我可以迭代 sys.stdin 而无需先通过 .readline() 。但是,我非常感谢您在原始 while 条件下维护我的“后门”,以及列表理解。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2022-06-15
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多