snippets / Alter items in a sequence according to a translation table

Language: Python - First posted by rmurri on 2007-11-17 00:14 (10 months, 3 weeks)
Link to the snippet: http://www.friendsnippets.org/snippet/120/

This is the analogue of Python str.translate or unicode.translate for general iterables (lists, tuples, etc.) Tested with Python 2.5

 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
In order to post a comment, you should have a friendsnippet account. Please sign-in.

0 comments

Nov '07
  • This is the analogue of Python `str.translate` or `unicode.translate` for general iterables (lists, tuples, etc.) Tested with Python 2.5

Common Tags



snippet History

Nov '07