problems when unpacking tuple ...
John Machin
sjmachin at lexicon.net
Sat Apr 22 19:26:30 EDT 2006
On 23/04/2006 2:21 AM, harold wrote:
> Dear all,
>
> Maybe I stared on the monitor for too long, because I cannot find the
> bug ...
You already have your answer, but below are clues on how to solve such
problems much faster by yourself.
> My script "transition_filter.py" starts with the following lines:
>
> import sys
>
> for line in sys.stdin :
> try :
> for a,b,c,d in line.split() :
> pass
>
> except ValueError , err :
> print line.split()
> raise err
>
> The output (when given the data I want to parse) is:
> ['0.0','1','0.04','0']
I doubt it. Much more likely is
['0.0', '1', '0.04', '0']
It doesn't matter in this case, but you should really get into the
habit of copy/pasting *EXACTLY* what is there, not re-typing what you
think is there.
> Traceback (most recent call last):
> File "transition_filter.py", line 10, in ?
> raise err
> ValueError: need more than 3 values to unpack
>
> What is going wrong here? Why does python think that
> I want to unpack the outcome of line.split() into three
> values instead of four? I must be really tired, but I just
> cannot see the problem. Any clues??
>
Clues:
1. Use the print statement to show what you have.
2. Use the built-in repr() function to show *unambiguously* what you
have -- very important when you get into Unicode and encoding/decoding
problems; what you see after "print foo" is not necessarily what
somebody using a different locale/codepage will see.
3. In some cases (not this one), it is also helpful to print the type()
of the data item.
Example:
C:\junk>type harold.py
import sys
def harold1():
for line in sys.stdin :
try :
for a,b,c,d in line.split() :
pass
except ValueError , err :
print line.split()
raise err
def harold2():
for line in sys.stdin:
print "line =", repr(line)
split_result = line.split()
print "split result =", repr(split_result)
for x in split_result:
print "about to try to unpack the sequence", repr(x), "into
4 items"
a, b, c, d = x
harold2()
C:\junk>harold.py
0.0 1 0.04 0
a b c d e f
^Z
line = '0.0 1 0.04 0\n'
split result = ['0.0', '1', '0.04', '0']
about to try to unpack the sequence '0.0' into 4 items
Traceback (most recent call last):
File "C:\junk\harold.py", line 22, in ?
harold2()
File "C:\junk\harold.py", line 20, in harold2
a, b, c, d = x
ValueError: need more than 3 values to unpack
=====
Coding style: Not inventing and using your own dialect makes two-way
communication much easier in any language (computer or human). Consider
reading and following http://www.python.org/dev/peps/pep-0008/
Hope this helps,
John
More information about the Python-list
mailing list