示例#1
0
文件: xmap.py 项目: lcrees/blade
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))
示例#2
0
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))
示例#3
0
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),
    )