如何在python列表中接受来自文件的数据流

如何在python列表中接受来自文件的数据流,python,stream,stdout,stdin,Python,Stream,Stdout,Stdin,我应该在python中附加STDIN中的所有整数值 例如: 5 6 0 4 2 4 1 0 0 4 result = [] try: a = raw_input() while a: result.append(int(a)) a = raw_input() except EOFError: pass 假设下面是来自stdin的整数,如何将这些值附加到列表中 我的代码: result = [] try: while raw_

我应该在python中
附加
STDIN
中的所有整数值

例如:

5
6
0
4
2
4
1
0
0
4
result = []

try:
    a = raw_input()
    while a:
        result.append(int(a))
        a = raw_input()
except EOFError:
    pass
假设下面是来自stdin的整数,如何将这些值附加到
列表中

我的代码:

result = []

try:
    while raw_input():
        a = raw_input()
        result.append(int(a))
except EOFError:
    pass

print result
有人能帮我吗?多谢各位

结果只是打印[6,4,4,0,4]


当您在while行中每秒消耗一次原始输入时,将其更改为测试“a”是否为非null。例如:

5
6
0
4
2
4
1
0
0
4
result = []

try:
    a = raw_input()
    while a:
        result.append(int(a))
        a = raw_input()
except EOFError:
    pass

打印结果

如果在while行中每秒消耗一次原始输入,请将此更改为测试“a”是否为非空。例如:

5
6
0
4
2
4
1
0
0
4
result = []

try:
    a = raw_input()
    while a:
        result.append(int(a))
        a = raw_input()
except EOFError:
    pass

打印结果

好的,我的问题已通过
文件输入
模块解决

import fileinput

for line in fileinput.input():
    print line

好的,我的问题通过
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
将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\u 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的一般说明。类似流的对象,包括为读取而打开的文件、stdin和
StringIO
等,都有一个迭代器,可以在这些行上进行迭代。因此,您的程序可以简化为pythonic

import sys
result = [int(line) for line in sys.stdin]

问题是您调用了
raw\u 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的一般说明。类似流的对象,包括为读取而打开的文件、stdin和
StringIO
等,都有一个迭代器,可以在这些行上进行迭代。因此,您的程序可以简化为pythonic

import sys
result = [int(line) for line in sys.stdin]

您能举个例子吗?您每天调用
raw\u input
两次loop@walpen如果你写下你的答案,我将投票并接受它。你说得对。你能举个例子吗?你每天调用
raw\u input
两次loop@walpen如果你写下你的答案,我将投票并接受它。你说得对