當前位置: 首頁>>代碼示例>>Python>>正文


Python itertools.repeat方法代碼示例

本文整理匯總了Python中itertools.repeat方法的典型用法代碼示例。如果您正苦於以下問題:Python itertools.repeat方法的具體用法?Python itertools.repeat怎麽用?Python itertools.repeat使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在itertools的用法示例。


在下文中一共展示了itertools.repeat方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: timeit

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def timeit(self, number=default_number):
        """Time 'number' executions of the main statement.

        To be precise, this executes the setup statement once, and
        then returns the time it takes to execute the main statement
        a number of times, as a float measured in seconds.  The
        argument is the number of times through the loop, defaulting
        to one million.  The main statement, the setup statement and
        the timer function to be used are passed to the constructor.
        """
        it = itertools.repeat(None, number)
        gcold = gc.isenabled()
        gc.disable()
        try:
            timing = self.inner(it, self.timer)
        finally:
            if gcold:
                gc.enable()
        return timing 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:21,代碼來源:timeit.py

示例2: repeat

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def repeat(self, repeat=default_repeat, number=default_number):
        """Call timeit() a few times.

        This is a convenience function that calls the timeit()
        repeatedly, returning a list of results.  The first argument
        specifies how many times to call timeit(), defaulting to 3;
        the second argument specifies the timer argument, defaulting
        to one million.

        Note: it's tempting to calculate mean and standard deviation
        from the result vector and report these.  However, this is not
        very useful.  In a typical case, the lowest value gives a
        lower bound for how fast your machine can run the given code
        snippet; higher values in the result vector are typically not
        caused by variability in Python's speed, but by other
        processes interfering with your timing accuracy.  So the min()
        of the result is probably the only number you should be
        interested in.  After that, you should look at the entire
        vector and apply common sense rather than statistics.
        """
        r = []
        for i in range(repeat):
            t = self.timeit(number)
            r.append(t)
        return r 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:27,代碼來源:timeit.py

示例3: elements

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.items()))

    # Override dict methods where necessary 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:25,代碼來源:__init__.py

示例4: elements

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def elements(self):
                '''Iterator over elements repeating each as many times as its count.

                >>> c = Counter('ABCABC')
                >>> sorted(c.elements())
                ['A', 'A', 'B', 'B', 'C', 'C']

                If an element's count has been set to zero or is a negative number,
                elements() will ignore it.

                '''
                for elem, count in self.iteritems():
                    for _ in repeat(None, count):
                        yield elem

            # Override dict methods where the meaning changes for Counter
            # objects. 
開發者ID:rafasashi,項目名稱:razzy-spinner,代碼行數:19,代碼來源:compat.py

示例5: ExtractFeaturesForDirsList

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def ExtractFeaturesForDirsList(args, dirs):
    global TMP_DIR
    TMP_DIR = "./tmp/feature_extractor%d/" % (os.getpid())
    if os.path.exists(TMP_DIR):
        shutil.rmtree(TMP_DIR, ignore_errors=True)
    os.makedirs(TMP_DIR)
    try:
        p = multiprocessing.Pool(4)
        p.starmap(ParallelExtractDir, zip(itertools.repeat(args), dirs))
        #for dir in dirs:
        #    ExtractFeaturesForDir(args, dir, '')
        output_files = os.listdir(TMP_DIR)
        for f in output_files:
            os.system("cat %s/%s" % (TMP_DIR, f))
    finally:
        shutil.rmtree(TMP_DIR, ignore_errors=True) 
開發者ID:tech-srl,項目名稱:code2vec,代碼行數:18,代碼來源:extract.py

示例6: delete_lines

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def delete_lines(self, count=None):
        """Deletes the indicated # of lines, starting at line with
        cursor. As lines are deleted, lines displayed below cursor
        move up. Lines added to bottom of screen have spaces with same
        character attributes as last line moved up.

        :param int count: number of lines to delete.
        """
        count = count or 1
        top, bottom = self.margins

        # If cursor is outside scrolling margins it -- do nothin'.
        if top <= self.cursor.y <= bottom:
            #                v -- +1 to include the bottom margin.
            for _ in range(min(bottom - self.cursor.y + 1, count)):
                self.buffer.pop(self.cursor.y)
                self.buffer.insert(bottom, list(
                    repeat(self.cursor.attrs, self.columns)))

            self.carriage_return() 
開發者ID:Wramberg,項目名稱:TerminalView,代碼行數:22,代碼來源:screens.py

示例7: __make_date_examples

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def __make_date_examples():
    dates_no_day = [
        date(1999, 12, 1),
        date(2016, 2, 1)
    ]

    if six.PY3:
        # strftime does not support dates before 1900 in Python 2
        dates_no_day.append(date(1000, 11, 1))

    # Only one supported format for dates with no day
    o = zip(dates_no_day, it.repeat('%Y-%m'))

    dates_w_day = [
        date(1969, 12, 31),
        date(1900, 1, 1),
        date(2016, 2, 29),
        date(2017, 11, 14)
    ]

    dates_w_day_fmts = ('%Y%m%d', '%Y-%m-%d')
    o = it.chain(o, it.product(dates_w_day, dates_w_day_fmts))

    return list(o) 
開發者ID:MediaBrowser,項目名稱:plugin.video.emby,代碼行數:26,代碼來源:test_isoparser.py

示例8: test_constructor_compound_dtypes

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def test_constructor_compound_dtypes(self):
        # GH 5191
        # compound dtypes should raise not-implementederror

        def f(dtype):
            data = list(itertools.repeat((datetime(2001, 1, 1),
                                          "aa", 20), 9))
            return DataFrame(data=data,
                             columns=["A", "B", "C"],
                             dtype=dtype)

        pytest.raises(NotImplementedError, f,
                      [("A", "datetime64[h]"),
                       ("B", "str"),
                       ("C", "int32")])

        # these work (though results may be unexpected)
        f('int64')
        f('float64')

        # 10822
        # invalid error message on dt inference
        if not compat.is_platform_windows():
            f('M8[ns]') 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:test_block_internals.py

示例9: _hash_comparison

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def _hash_comparison(self):
        """
        Return a comparison of actual and expected hash values.

        Example::

               Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
                            or 123451234512345123451234512345123451234512345
                    Got        bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef

        """
        def hash_then_or(hash_name):
            # For now, all the decent hashes have 6-char names, so we can get
            # away with hard-coding space literals.
            return chain([hash_name], repeat('    or'))

        lines = []
        for hash_name, expecteds in iteritems(self.allowed):
            prefix = hash_then_or(hash_name)
            lines.extend(('        Expected %s %s' % (next(prefix), e))
                         for e in expecteds)
            lines.append('             Got        %s\n' %
                         self.gots[hash_name].hexdigest())
            prefix = '    or'
        return '\n'.join(lines) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:27,代碼來源:exceptions.py

示例10: get

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def get(self, idx):
        data = self.data.__class__()

        if hasattr(self.data, '__num_nodes__'):
            data.num_nodes = self.data.__num_nodes__[idx]

        for key in self.data.keys:
            item, slices = self.data[key], self.slices[key]
            start, end = slices[idx].item(), slices[idx + 1].item()
            # print(slices[idx], slices[idx + 1])
            if torch.is_tensor(item):
                s = list(repeat(slice(None), item.dim()))
                s[self.data.__cat_dim__(key, item)] = slice(start, end)
            elif start + 1 == end:
                s = slices[start]
            else:
                s = slice(start, end)
            data[key] = item[s]
        return data 
開發者ID:rusty1s,項目名稱:pytorch_geometric,代碼行數:21,代碼來源:in_memory_dataset.py

示例11: matchPreviousLiteral

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def matchPreviousLiteral(expr):
    """Helper to define an expression that is indirectly defined from
       the tokens matched in a previous expression, that is, it looks
       for a 'repeat' of a previous expression.  For example::
           first = Word(nums)
           second = matchPreviousLiteral(first)
           matchExpr = first + ":" + second
       will match C{"1:1"}, but not C{"1:2"}.  Because this matches a
       previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
       If this is not desired, use C{matchPreviousExpr}.
       Do *not* use with packrat parsing enabled.
    """
    rep = Forward()
    def copyTokenToRepeater(s,l,t):
        if t:
            if len(t) == 1:
                rep << t[0]
            else:
                # flatten t tokens
                tflat = _flatten(t.asList())
                rep << And( [ Literal(tt) for tt in tflat ] )
        else:
            rep << Empty()
    expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
    return rep 
開發者ID:jpush,項目名稱:jbox,代碼行數:27,代碼來源:pyparsing.py

示例12: matchPreviousExpr

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def matchPreviousExpr(expr):
    """Helper to define an expression that is indirectly defined from
       the tokens matched in a previous expression, that is, it looks
       for a 'repeat' of a previous expression.  For example::
           first = Word(nums)
           second = matchPreviousExpr(first)
           matchExpr = first + ":" + second
       will match C{"1:1"}, but not C{"1:2"}.  Because this matches by
       expressions, will *not* match the leading C{"1:1"} in C{"1:10"};
       the expressions are evaluated first, and then compared, so
       C{"1"} is compared with C{"10"}.
       Do *not* use with packrat parsing enabled.
    """
    rep = Forward()
    e2 = expr.copy()
    rep <<= e2
    def copyTokenToRepeater(s,l,t):
        matchTokens = _flatten(t.asList())
        def mustMatchTheseTokens(s,l,t):
            theseTokens = _flatten(t.asList())
            if  theseTokens != matchTokens:
                raise ParseException("",0,"")
        rep.setParseAction( mustMatchTheseTokens, callDuringTry=True )
    expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
    return rep 
開發者ID:jpush,項目名稱:jbox,代碼行數:27,代碼來源:pyparsing.py

示例13: populate_obj

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def populate_obj(self, obj, name):
        values = getattr(obj, name, None)
        try:
            ivalues = iter(values)
        except TypeError:
            ivalues = iter([])

        candidates = itertools.chain(ivalues, itertools.repeat(None))
        _fake = type(str('_fake'), (object, ), {})
        output = []
        for field, data in izip(self.entries, candidates):
            fake_obj = _fake()
            fake_obj.data = data
            field.populate_obj(fake_obj, 'data')
            output.append(fake_obj.data)

        setattr(obj, name, output) 
開發者ID:jpush,項目名稱:jbox,代碼行數:19,代碼來源:core.py

示例14: object_from_row

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def object_from_row(self, row, row_number, exception_policy=TableSheetExceptionPolicy.RaiseCellException):
        data = OrderedDict()
        cell_exceptions = []
        for cell, column in zip(chain(row, repeat(None)), self.columns):
            try:
                data[column.object_attribute] = column._from_excel(cell)
            except CellException as e:
                if exception_policy.value <= TableSheetExceptionPolicy.RaiseCellException.value:
                    raise e
                else:
                    cell_exceptions.append(e)

        if cell_exceptions:
            raise CellExceptions(cell_exceptions)

        # return self.row_class(**data)
        return self.create_object(row_number, **data) 
開發者ID:SverkerSbrg,項目名稱:openpyxl-templates,代碼行數:19,代碼來源:table_sheet.py

示例15: alter_allocations

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import repeat [as 別名]
def alter_allocations(self, keys, quota_sizes=None, handle_shrink=True, new_keys=None,
                          allocate=False, process_quota=False):
        """
        Alter multiple requests
        :param keys: keys to update
        :param quota_sizes: new quota sizes, if None, no changes will be made
        :param handle_shrink: if True and the quota size less than the original, process requests in the queue
        :param new_keys: new allocation keys to replace current keys, if None, no changes will be made
        :param allocate: if True, will allocate resources for new items
        :param process_quota: call process_quotas() after allocated
        :return:
        """
        quota_sizes = quota_sizes or itertools.repeat(None)
        new_keys = new_keys or itertools.repeat(None)
        shrink = False
        for k, s, nk in zip(keys, quota_sizes, new_keys):
            cur_shrink = self.alter_allocation(
                k, s, handle_shrink=False, new_key=nk, allocate=allocate, process_quota=process_quota)
            shrink = shrink or cur_shrink
        if shrink and handle_shrink:
            self._process_requests() 
開發者ID:mars-project,項目名稱:mars,代碼行數:23,代碼來源:quota.py


注:本文中的itertools.repeat方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。