def xinvoke(iterable, name, *args, **kw): ''' Feed global :term:`positional argument`\s and :term:`keyword argument`\s to each items in `iterable`'s `name` :term:`method`. .. note:: The original thing is returned if the return value of :term:`method` `name` is :data:`None`. :argument iterable: :term:`iterable` :argument str name: method name >>> from blade.xmap import xinvoke >>> # invoke list.index() >>> list(xinvoke([[5, 1, 7], [3, 2, 1]], 'index', 1)) [1, 2] >>> # invoke list.sort() but return sorted list instead of None >>> list(xinvoke([[5, 1, 7], [3, 2, 1]], 'sort')) [[1, 5, 7], [1, 2, 3]] ''' def invoke(caller, thing): read = caller(thing) return thing if read is None else read return partmap(invoke, iterable, methodcaller(name, *args, **kw))
def xsample(iterable, n): ''' Randomly :term:`slice` off `n` items in `iterable`. :argument iterable: :term:`iterable` :argument int n: sample size :return: :term:`iterator` of items >>> from blade.xslice import xsample >>> list(xsample([1, 2, 3, 4, 5, 6], 3)) # doctest: +SKIP [2, 4, 5] ''' i1, i2 = tee(iterable) return partmap( lambda i, r, c, x: i(x, r(0, c)), tee(i2, n), islice, randrange, count(i1), )