snippet: view plain - save this
1 class itranslate:
2 """Return items from a sequence, substituting them as specified.
3
4 First c'tor argument `subst` is a dictionary, specifying
5 substitutions to be applied. If an item matches a key of the
6 `subst` dictionary, the associated dictionary value is returned
7 instead; unless the value is `None`, in which case the item is
8 skipped altogether.
9
10 *Note:* you should use an appropriate `dict`-subclass if you want
11 to translate items which are not immutable.
12
13 Examples::
14 >>> list(itranslate({0:None, 3:2}, [2,1,0,0,1,3]))
15 [2, 1, 1, 2]
16 """
17 def __init__(self, subst, iterable):
18 self.mappings = subst
19 self.iterable = iter(iterable)
20 def __iter__(self):
21 return self
22 def next(self):
23 while True:
24 next = self.iterable.next()
25 if not self.mappings.has_key(next):
26 return next
27 translated = self.mappings[next]
28 if translated is None:
29 # skip this item
30 continue
31 return translated

0 comments