I want to read input from STDIN like this:
1,0
0,0
1,0
1,0
and so on until the new line is empty(\\n). This signifies the end of the input.
I did this
while (raw_input()!='\n'):
actual,predicted=raw_input().split(',')
Gave me this error when I entered "enter" in last input
0,0
0,1
1,0
1,1
1,1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-3ec5186ad531> in <module>()
5
6 while (raw_input()!='\n'):
----> 7 actual,predicted=raw_input().split(',')
8 if (actual==1 and predicted==1):
9 t_p+=50
ValueError: need more than 1 value to unpack
What's wrong?
OK, there are two problems here: raw_input strips the trailing newline, so a blank input becomes an empty string, not a newline.
The larger issue is that raw_input consumes the input, so your code won't work properly - it will only process every second line. The while loop calls raw_input (which uses up some input and discards it), then the body of the loop calls it again and assigns it to actual and predicted.
The python idiom for this task is a while True:
loop containing a break
:
while True:
line = raw_input()
if not line:
break
actual, predicted = line.split(",")
print("a, p", actual, predicted)
print("done!")
raw_input()
strips the trailing newline, so you want to compare to ''
.
But you're also reading two lines at a time in your loop, where I think you want something more like:
data = raw_input()
while (data != ''):
actual,predicted=data.split(',')
data = raw_input()
raw_input
is really used when you're writing a user-interactive program. It sounds like your program is a more typical UNIX program which processes file input.
sys.stdin
is an open file. Because of this, you can use my favorite feature of Python which is iterating over each line in a file. Ditch the raw_input
altogether and just treat your data as if it were a file:
for line in sys.stdin:
line = line.strip()
parts = line.split(',')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.