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


Python collections.Iterator方法代碼示例

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


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

示例1: _standardize_value

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def _standardize_value(self, value):
        reader, fsize, fname = (value + [None, None])[:3]

        if isinstance(reader, file):
            reader = self._make_file_reader(reader)

        elif isinstance(reader, str):
            reader = self._make_str_reader(reader)
            fsize = len(value[0])

        elif isinstance(reader, Iterator):
            pass

        else:
            raise InvalidArgumentTypeError('type of value[0] {x}'
                'is invalid'.format(x=type(value[0])))

        return reader, fsize, fname 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:20,代碼來源:multipart.py

示例2: axis_iter

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def axis_iter(self, axes=0):
        """Returns an iterator yielding Sub-MPArrays of ``self`` by iterating
        over the specified physical axes.

        **Example:** If ``self`` represents a bipartite (i.e. length 2)
        array with 2 physical dimensions on each site ``A[(k,l), (m,n)]``,
        ``self.axis_iter(0)`` is equivalent to::

            (A[(k, :), (m, :)] for m in range(...) for k in range(...))

        :param axes: Iterable or int specifiying the physical axes to iterate
            over (default 0 for each site)
        :returns: Iterator over :class:`.MPArray`

        """
        if not isinstance(axes, collections.Iterable):
            axes = it.repeat(axes, len(self))

        ltens_iter = it.product(*(iter(np.rollaxis(lten, i + 1))
                                  for i, lten in zip(axes, self.lt)))
        return (MPArray(ltens) for ltens in ltens_iter)

    ##########################
    #  Algebraic operations  #
    ########################## 
開發者ID:dsuess,項目名稱:mpnum,代碼行數:27,代碼來源:mparray.py

示例3: _extract_factors

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def _extract_factors(tens, ndims):
    """Extract iteratively the leftmost MPO tensor with given number of
    legs by a qr-decomposition

    :param np.ndarray tens: Full tensor to be factorized
    :param ndims: Number of physical legs per site or iterator over number of
        physical legs
    :returns: List of local tensors with given number of legs yielding a
        factorization of tens
    """
    current = next(ndims) if isinstance(ndims, collections.Iterator) else ndims
    if tens.ndim == current + 2:
        return [tens]
    elif tens.ndim < current + 2:
        raise AssertionError("Number of remaining legs insufficient.")
    else:
        unitary, rest = qr(tens.reshape((np.prod(tens.shape[:current + 1]), -1)))

        unitary = unitary.reshape(tens.shape[:current + 1] + rest.shape[:1])
        rest = rest.reshape(rest.shape[:1] + tens.shape[current + 1:])

        return [unitary] + _extract_factors(rest, ndims) 
開發者ID:dsuess,項目名稱:mpnum,代碼行數:24,代碼來源:mparray.py

示例4: _ltens_to_array

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def _ltens_to_array(ltens):
    """Computes the full array representation from an iterator yielding the
    local tensors. Note that it does not get rid of virtual legs.

    :param ltens: Iterator over local tensors
    :returns: numpy.ndarray representing the contracted MPA

    """
    ltens = ltens if isinstance(ltens, collections.Iterator) else iter(ltens)
    res = first = next(ltens)
    for tens in ltens:
        res = matdot(res, tens)
    if res is first:
        # Always return a writable array, even if len(ltens) == 1.
        res = res.copy()
    return res


################################################
#  Helper methods for variational compression  #
################################################ 
開發者ID:dsuess,項目名稱:mpnum,代碼行數:23,代碼來源:mparray.py

示例5: test_glob_common

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def test_glob_common(self):
        def _check(glob, expected):
            self.assertEqual(set(glob), { P(BASE, q) for q in expected })
        P = self.cls
        p = P(BASE)
        it = p.glob("fileA")
        self.assertIsInstance(it, collections.Iterator)
        _check(it, ["fileA"])
        _check(p.glob("fileB"), [])
        _check(p.glob("dir*/file*"), ["dirB/fileB", "dirC/fileC"])
        if symlink_skip_reason:
            _check(p.glob("*A"), ['dirA', 'fileA'])
        else:
            _check(p.glob("*A"), ['dirA', 'fileA', 'linkA'])
        if symlink_skip_reason:
            _check(p.glob("*B/*"), ['dirB/fileB'])
        else:
            _check(p.glob("*B/*"), ['dirB/fileB', 'dirB/linkD',
                                    'linkB/fileB', 'linkB/linkD'])
        if symlink_skip_reason:
            _check(p.glob("*/fileB"), ['dirB/fileB'])
        else:
            _check(p.glob("*/fileB"), ['dirB/fileB', 'linkB/fileB']) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:25,代碼來源:test_pathlib.py

示例6: test_rglob_common

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def test_rglob_common(self):
        def _check(glob, expected):
            self.assertEqual(set(glob), { P(BASE, q) for q in expected })
        P = self.cls
        p = P(BASE)
        it = p.rglob("fileA")
        self.assertIsInstance(it, collections.Iterator)
        # XXX cannot test because of symlink loops in the test setup
        #_check(it, ["fileA"])
        #_check(p.rglob("fileB"), ["dirB/fileB"])
        #_check(p.rglob("*/fileA"), [""])
        #_check(p.rglob("*/fileB"), ["dirB/fileB"])
        #_check(p.rglob("file*"), ["fileA", "dirB/fileB"])
        # No symlink loops here
        p = P(BASE, "dirC")
        _check(p.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"])
        _check(p.rglob("*/*"), ["dirC/dirD/fileD"]) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:19,代碼來源:test_pathlib.py

示例7: test_rglob_common

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def test_rglob_common(self):
        def _check(glob, expected):
            self.assertEqual(set(glob), { P(BASE, q) for q in expected })
        P = self.cls
        p = P(BASE)
        it = p.rglob("fileA")
        self.assertIsInstance(it, collections.Iterator)
        _check(it, ["fileA"])
        _check(p.rglob("fileB"), ["dirB/fileB"])
        _check(p.rglob("*/fileA"), [])
        if symlink_skip_reason:
            _check(p.rglob("*/fileB"), ["dirB/fileB"])
        else:
            _check(p.rglob("*/fileB"), ["dirB/fileB", "dirB/linkD/fileB",
                                        "linkB/fileB", "dirA/linkC/fileB"])
        _check(p.rglob("file*"), ["fileA", "dirB/fileB",
                                  "dirC/fileC", "dirC/dirD/fileD"])
        p = P(BASE, "dirC")
        _check(p.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"])
        _check(p.rglob("*/*"), ["dirC/dirD/fileD"]) 
開發者ID:IronLanguages,項目名稱:ironpython3,代碼行數:22,代碼來源:test_pathlib.py

示例8: testIsIterator

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def testIsIterator():
    print("是否為Iterable對象:")
    print(isinstance([], Iterable))
    print(isinstance({}, Iterable))
    print(isinstance((1, 2, 3), Iterable))
    print(isinstance(set([1, 2, 3]), Iterable))
    print(isinstance("string", Iterable))
    print(isinstance(gen, Iterable))
    print(isinstance(fibonacci(10), Iterable))
    print("是否為Iterator對象:")
    print(isinstance([], Iterator))
    print(isinstance({}, Iterator))
    print(isinstance((1, 2, 3), Iterator))
    print(isinstance(set([1, 2, 3]), Iterator))
    print(isinstance("string", Iterator))
    print(isinstance(gen, Iterator))
    print(isinstance(fibonacci(10), Iterator)) 
開發者ID:luoweifu,項目名稱:PyDesignPattern,代碼行數:19,代碼來源:Iterator.py

示例9: _prepare_data

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def _prepare_data(self, data):
        """
        Prepare data for addition to the tree. If the data is a list or tuple,
        it is expected to be of the form (obj, lookup_type, value), where obj
        is a Constraint object, and is then slightly munged before being
        stored (to avoid storing any reference to field objects). Otherwise,
        the 'data' is stored unchanged and can be any class with an 'as_sql()'
        method.
        """
        if not isinstance(data, (list, tuple)):
            return data
        obj, lookup_type, value = data
        if isinstance(value, collections.Iterator):
            # Consume any generators immediately, so that we can determine
            # emptiness and transform any non-empty values correctly.
            value = list(value)

        # The "value_annotation" parameter is used to pass auxiliary information
        # about the value(s) to the query construction. Specifically, datetime
        # and empty values need special handling. Other types could be used
        # here in the future (using Python types is suggested for consistency).
        if (isinstance(value, datetime.datetime)
                or (isinstance(obj.field, DateTimeField) and lookup_type != 'isnull')):
            value_annotation = datetime.datetime
        elif hasattr(value, 'value_annotation'):
            value_annotation = value.value_annotation
        else:
            value_annotation = bool(value)

        if hasattr(obj, 'prepare'):
            value = obj.prepare(lookup_type, value)
        return (obj, lookup_type, value_annotation, value) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:34,代碼來源:where.py

示例10: _get_choices

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def _get_choices(self):
        if isinstance(self._choices, collections.Iterator):
            choices, self._choices = tee(self._choices)
            return choices
        else:
            return self._choices 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:8,代碼來源:__init__.py

示例11: test_Iterator

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def test_Iterator(self):
        non_samples = [None, 42, 3.14, 1j, "".encode('ascii'), "", (), [],
            {}, set()]
        for x in non_samples:
            self.assertNotIsInstance(x, Iterator)
            self.assertFalse(issubclass(type(x), Iterator), repr(type(x)))
        samples = [iter(str()),
                   iter(tuple()), iter(list()), iter(dict()),
                   iter(set()), iter(frozenset()),
                   iter(dict().keys()), iter(dict().items()),
                   iter(dict().values()),
                   (lambda: (yield))(),
                   (x for x in []),
                   ]
        for x in samples:
            self.assertIsInstance(x, Iterator)
            self.assertTrue(issubclass(type(x), Iterator), repr(type(x)))
        self.validate_abstract_methods(Iterator, 'next', '__iter__')

        # Issue 10565
        class NextOnly:
            def __next__(self):
                yield 1
                raise StopIteration
        self.assertNotIsInstance(NextOnly(), Iterator)
        class NextOnlyNew(object):
            def __next__(self):
                yield 1
                raise StopIteration
        self.assertNotIsInstance(NextOnlyNew(), Iterator) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:32,代碼來源:test_collections.py

示例12: test_direct_subclassing

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def test_direct_subclassing(self):
        for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
            class C(B):
                pass
            self.assertTrue(issubclass(C, B))
            self.assertFalse(issubclass(int, C)) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:8,代碼來源:test_collections.py

示例13: test_registration

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def test_registration(self):
        for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
            class C:
                __metaclass__ = type
                __hash__ = None  # Make sure it isn't hashable by default
            self.assertFalse(issubclass(C, B), B.__name__)
            B.register(C)
            self.assertTrue(issubclass(C, B)) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:10,代碼來源:test_collections.py

示例14: test_iter

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def test_iter(self):
        self.assertIsInstance(languages, collections.Iterable)
        self.assertIsInstance(iter(languages), collections.Iterator) 
開發者ID:noumar,項目名稱:iso639,代碼行數:5,代碼來源:tests.py

示例15: testMyIteratableObj

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Iterator [as 別名]
def testMyIteratableObj():
    myList = MyList()
    print("iterator是迭代器:%s" % isinstance(iter(myList), Iterator))

    print("myList是可迭代的對象:%s" % isinstance(myList, Iterable))

    for temp in myList:
        print(temp) 
開發者ID:HaoZhang95,項目名稱:Python24,代碼行數:10,代碼來源:basic02.py


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