我用python编写了以下代码:
#!/usr/bin/python
import sys
def reducer():
oldKey = None
totalSales = 0
for line in sys.stdin:
data= line.strip().split("\t")
if(len(data)!=2):
continue
thisKey,thisSale = data
if (oldKey and oldKey != thisKey):
print ("{}\t{}".format(oldKey,totalSales))
oldKey=thisKey
totalSales = 0
oldKey = thisKey
totalSales += float(thisSale)
if(oldKey!=None):
print("{}\t{}".format(oldKey,totalSales))
reducer()
当我给出输入时:
a 1
a 2
a 3
b 4
b 5
b 6
c 1
c 2
然后在此处按Ctrl+D
我得到输出:
a 6.0
b 15.0
我预期的结果是:
a 6.0
b 15.0
c 3.0
只有在我再次按下Ctrl+D之后,我才能得到完整的输出。为什么会这样?我该怎么修?你知道吗
文件对象迭代(
for line in sys.stdin: ..
)内部缓冲会导致您观察到的行为。你知道吗通过使用
sys.stdin.readline()
和while
循环,可以避免这种情况。你知道吗更改以下行:
使用:
相关PYTHON(1)手册页部分:
相关问题 更多 >
编程相关推荐