[Python-Dev] itertools additions: one(), single_valued() (original) (raw)
Raymond Hettinger python at rcn.com
Mon May 26 21:27:56 CEST 2008
- Previous message: [Python-Dev] itertools additions: one(), single_valued()
- Next message: [Python-Dev] itertools additions: one(), single_valued()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
[Andreas]
I find the following two operations functions useful and general enough that I would like to propose them for addition to itertools:
No thanks. Variants can already be constructed from existing tools. And, they seem a little to specific to a data model where the first entry has some special significance depending on whether or not it is unique.
it = iter(iterable) try: firstitem = it.next() except StopIteration: raise ValueError, "empty iterable passed to 'singlevalued()'" for otheritem in it: if otheritem != firstitem: raise ValueError, "non-single-valued iterable'" return firstitem
This looks like a set() operation with a couple odd special cases for exceptions.
[] --> ValueError If [x] --> x [x x x] --> x [x x y x] --> ValueError
The two non-exception cases both run the input iterable to exhaustion and as such do not fit it with the lazy-evaluation theme of the itertools module.
def one(iterable): it = iter(iterable) try: v = it.next() except StopIteration: raise ValueError, "empty iterable passed to 'one()'" try: v2 = it.next() raise ValueError, "iterable with more than one entry passed to 'one()'" except StopIteration: return v
Looks similar to list(islice(iterable,2)) followed by regular list-like handling.
whatiamlookingfor = one(item for item in items if predicate(item))
Looks similar to: wialf = ifilter(pred, items).next()
This also encodes and checks the assumption that the sought item is unique within the list of candidates. Again, the assertion part could be turned off in optimized mode.
That is an odd assumption given that you're searching for a predicate match and not a single item match. Also, it is often a better design to enforce uniqueness constraints upon insertion, not upon lookup.
Raymond
- Previous message: [Python-Dev] itertools additions: one(), single_valued()
- Next message: [Python-Dev] itertools additions: one(), single_valued()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]