In the examples section, show how zip() is reversible.

Patches to the reference implementation:

    __getitem__() raises IndexError immediately if no sequences were
    given.

    __len__() returns 0 if no sequences were given.

    __cmp__() new method

Added a little more explanation to raise-a-TypeError-for-zip(a)

Added `fold' as one of the alternative names proposed.
This commit is contained in:
Barry Warsaw 2000-07-19 04:19:54 +00:00
parent 6f232833de
commit f25a70097b
1 changed files with 53 additions and 4 deletions

View File

@ -172,6 +172,26 @@ Examples
>>> map(None, a, b, c, d)
[(1, 5, 9, 12), (2, 6, 10, 13), (3, 7, 11, None), (4, 8, None, None)]
Note that when the sequences are of the same length, zip() is
reversible:
>>> a = (1, 2, 3)
>>> b = (4, 5, 6)
>>> x = zip(a, b)
>>> y = zip(*x) # alternatively, apply(zip, x)
>>> z = zip(*y) # alternatively, apply(zip, y)
>>> x
[(1, 4), (2, 5), (3, 6)]
>>> y
[(1, 2, 3), (4, 5, 6)]
>>> z
[(1, 4), (2, 5), (3, 6)]
>>> x == z
1
It is not possible to reverse zip this way when the sequences are
not all the same length.
Reference Implementation
@ -195,6 +215,8 @@ Reference Implementation
self.__seqlen = len(args)
def __getitem__(self, i):
if not self.__sequences:
raise IndexError
ret = []
exhausted = 0
for s in self.__sequences:
@ -218,6 +240,8 @@ Reference Implementation
slen = len(s)
if shortest < 0 or slen < shortest:
shortest = slen
if shortest < 0:
return 0
return shortest
longest = 0
for s in self.__sequences:
@ -226,6 +250,30 @@ Reference Implementation
longest = slen
return longest
def __cmp__(self, other):
i = 0
smore = 1
omore = 1
while 1:
try:
si = self[i]
except IndexError:
smore = 0
try:
oi = other[i]
except IndexError:
omore = 0
if not smore and not omore:
return 0
elif not smore:
return -1
elif not omore:
return 1
test = cmp(si, oi)
if test:
return test
i = i + 1
def __str__(self):
ret = []
i = 0
@ -335,7 +383,8 @@ Open Issues
3) Raises TypeError
Pros: None
Pros: zip(a) doesn't make much sense and could be confusing
to explain.
Cons: needless restriction
@ -345,9 +394,9 @@ Open Issues
with the zip compression algorithm. Other suggestions include
(but are not limited to!): marry, weave, parallel, lace, braid,
interlace, permute, furl, tuples, lists, stitch, collate, knit,
plait, and with. All have disadvantages, and there is no clear
unanimous choice, therefore the decision was made to go with
`zip' because the same functionality is available in other
plait, fold, and with. All have disadvantages, and there is no
clear unanimous choice, therefore the decision was made to go
with `zip' because the same functionality is available in other
languages (e.g. Haskell) under the name `zip'[2].