如何接受来自列表 python 中文件的数据流
How to accept stream of data coming from a file in list python
我应该 append
python 中 STDIN
的所有整数值。
例如:
5
6
0
4
2
4
1
0
0
4
假设下面是来自标准输入的整数,如何将这些值附加到list
?
我的代码:
result = []
try:
while raw_input():
a = raw_input()
result.append(int(a))
except EOFError:
pass
print result
有人能帮帮我吗?谢谢
Result is only printing [6, 4, 4, 0, 4]
您正在消耗 while 行中的每一秒 raw_input,更改它以测试 'a' 是 non-null。例如:
result = []
try:
a = raw_input()
while a:
result.append(int(a))
a = raw_input()
except EOFError:
pass
打印结果
好的,我的问题已使用 fileinput
模块解决
import fileinput
for line in fileinput.input():
print line
将 while 循环中的 raw_input() 设置为变量(在您的情况下为 'a')应该可以解决问题。
result = []
a = raw_input("Enter integer pls:\n> ")
try:
while a is not '':
result.append(int(a))
a = raw_input("Enter another integer pls:\n> ")
except ValueError:
pass
print result
问题是你调用了两次raw_input()
。
while raw_input(): # this consumes a line, checks it, but does not do anything with the results
a = raw_input()
result.append(int(a))
关于 python 的一般说明。 Stream like objects,包括为读取而打开的文件、stdin 和 StringIO
等,都有一个迭代器来迭代那里的行。所以你的程序可以简化为 pythonic.
import sys
result = [int(line) for line in sys.stdin]
我应该 append
python 中 STDIN
的所有整数值。
例如:
5
6
0
4
2
4
1
0
0
4
假设下面是来自标准输入的整数,如何将这些值附加到list
?
我的代码:
result = []
try:
while raw_input():
a = raw_input()
result.append(int(a))
except EOFError:
pass
print result
有人能帮帮我吗?谢谢
Result is only printing [6, 4, 4, 0, 4]
您正在消耗 while 行中的每一秒 raw_input,更改它以测试 'a' 是 non-null。例如:
result = []
try:
a = raw_input()
while a:
result.append(int(a))
a = raw_input()
except EOFError:
pass
打印结果
好的,我的问题已使用 fileinput
模块解决
import fileinput
for line in fileinput.input():
print line
将 while 循环中的 raw_input() 设置为变量(在您的情况下为 'a')应该可以解决问题。
result = []
a = raw_input("Enter integer pls:\n> ")
try:
while a is not '':
result.append(int(a))
a = raw_input("Enter another integer pls:\n> ")
except ValueError:
pass
print result
问题是你调用了两次raw_input()
。
while raw_input(): # this consumes a line, checks it, but does not do anything with the results
a = raw_input()
result.append(int(a))
关于 python 的一般说明。 Stream like objects,包括为读取而打开的文件、stdin 和 StringIO
等,都有一个迭代器来迭代那里的行。所以你的程序可以简化为 pythonic.
import sys
result = [int(line) for line in sys.stdin]