[portland] zip() tutorial needed
Rich Shepard
rshepard at appl-ecosys.com
Mon Mar 31 23:08:27 CEST 2008
Not too long ago when I tried to specify x, y pairs to plot data, python
threw the exception of too many pairs to unpack. My original code and the
error was:
x,y = [(15.0, 0.0), (30.0, 1.0), (70.0, 1.0), (85.0, 0.0)]
ValueError: too many values to unpack
Someone on the matplotlib mail list wrote,
You are looking for the classic "unzip" trick:
x,y = zip(*[(15.0, 0.0), (30.0, 1.0), (70.0, 1.0), (85.0, 0.0)])
And sure enough, that solved the problem. However, I apparently don't
understand it well enough to apply it to a similar situation. Reading the
Python doc on built-in functions doesn't help me. I read,
"zip( [iterable, ...])
This function returns a list of tuples, where the i-th tuple contains
the i-th element from each of the argument sequences or iterables. The
returned list is truncated in length to the length of the shortest argument
sequence. When there are multiple arguments which are all of the same
length, zip() is similar to map() with an initial argument of None. With a
single sequence argument, it returns a list of 1-tuples. With no arguments,
it returns an empty list. New in version 2.0.
"Changed in version 2.4: Formerly, zip() required at least one argument
and zip() raised a TypeError instead of returning an empty list."
Which tells me that I should have a result that looks like my original
list of tuples. I think this is where I'm confused about what zip() is
doing.
Now, using a different plotting library, I'm running into the same error,
but the same solution is not working for me.
A curve-generating function in one model writes the x and y values to
separate lists in the common values module for the application. If I 'print
config.appData.plotX' and 'print config.appData.plotY', each list is printed
in succession. The values in each list are separated by spaces.
When I try to pass these lists to the plotting function I get an error
(which is specific to that library). So I tried unzipping the two lists but
I still get the error:
X, Y = zip(*[config.appData.plotX, config.appData.plotY])
ValueError: too many values to unpack
So, I'd appreciate learning more about what zip() does, and why it's not
giving me a list of x, y values.
Rich
--
Richard B. Shepard, Ph.D. | Integrity Credibility
Applied Ecosystem Services, Inc. | Innovation
<http://www.appl-ecosys.com> Voice: 503-667-4517 Fax: 503-667-8863
More information about the Portland
mailing list