i have a python code which should read in 2 integers from standard input till user presses Ctrl+D (i.e EOF)
and do some processing .I tried the following code :
n,k=map(int,[a for a in sys.stdin.read().split()])
Here , when i enter two integers the programme accepts it and when i press Ctrl+D it shows the correct output , like:
6 3
but when i put in 2 pairs in intergers like:
6 3
12 2
and then press Ctrl+D then instead of the desired result i get error that:
[i]ValueError: Too many values to upack[/i]
So how do i correct the code for it to work properly?
I intend开发者_如何学运维 to have the shortest possible code for that
Thanks.
>>> x=map(int,[a for a in sys.stdin.read().split()])
2 3 4 5
>>> x
[2, 3, 4, 5]
and work against the list; this so you will accept a variable number of ints if required to do so
The problem is not in how you read from stdin. Entering 6 3
essentially makes your code equivalent to
n, k = [6, 3]
which will work fine. Entering 6 3 12 2
though will result in
n, k = [6, 3, 12, 2]
which does not work, since you try to unpack a sequence of four values to only two targets. If you want to ignore everything beyond the first two numbers, try
n, k = [int(a) for a in sys.stdin.read().split()][:2]
If you want to iterate through the numbers read from stdin in pairs, you can use
numbers = (int(a) for a in sys.stdin.read().split())
for n, k in zip(numbers, numbers):
# whatever
精彩评论