Python - 从STDIN中解析多行数据并存储在标准数组中。

问题描述 投票:1回答:2

我经历了建议的类似问题,但是似乎遇到了死胡同;很可能是因为我没有充分解释我的问题.我试图获取一些我可以访问的 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
2个回答
1
投票

你可以迭代 sys.stdin (阅读更多 此处).

对于存储你的数字,只需写任何代码,将它们从字符串中提取出来,然后将数字追加到一个列表中。

下面是一个例子。

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']

每一个数字都是从文件中读取的。


1
投票

如果你真的想保留 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]
© www.soinside.com 2019 - 2024. All rights reserved.