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


Python collections.Set方法代碼示例

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


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

示例1: test_abc_registry

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def test_abc_registry(self):
        d = dict(a=1)

        self.assertIsInstance(d.viewkeys(), collections.KeysView)
        self.assertIsInstance(d.viewkeys(), collections.MappingView)
        self.assertIsInstance(d.viewkeys(), collections.Set)
        self.assertIsInstance(d.viewkeys(), collections.Sized)
        self.assertIsInstance(d.viewkeys(), collections.Iterable)
        self.assertIsInstance(d.viewkeys(), collections.Container)

        self.assertIsInstance(d.viewvalues(), collections.ValuesView)
        self.assertIsInstance(d.viewvalues(), collections.MappingView)
        self.assertIsInstance(d.viewvalues(), collections.Sized)

        self.assertIsInstance(d.viewitems(), collections.ItemsView)
        self.assertIsInstance(d.viewitems(), collections.MappingView)
        self.assertIsInstance(d.viewitems(), collections.Set)
        self.assertIsInstance(d.viewitems(), collections.Sized)
        self.assertIsInstance(d.viewitems(), collections.Iterable)
        self.assertIsInstance(d.viewitems(), collections.Container) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:22,代碼來源:test_dictviews.py

示例2: __call__

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def __call__(self, *args, **kwargs):
        """
        Executes child computations in parallel.

        :arg args: list of values to the placeholders specified in __init__ *args

        :return: tuple of return values, one per return specified in __init__ returns list.
        """
        args = self.unpack_args_or_feed_dict(args, kwargs)
        for child in itervalues(self.child_computations):
            child.feed_input([args[i] for i in child.param_idx])

        return_vals = dict()
        for child in itervalues(self.child_computations):
            return_vals.update(child.get_results())

        if isinstance(self.computation_op.returns, Op):
            return return_vals[self.computation_op.returns]
        elif isinstance(self.computation_op.returns, (collections.Sequence, OrderedSet)):
            return tuple(return_vals[op] for op in self.computation_op.returns)
        elif isinstance(self.computation_op.returns, collections.Set):
            return return_vals
        else:
            return None 
開發者ID:NervanaSystems,項目名稱:ngraph-python,代碼行數:26,代碼來源:hetrtransform.py

示例3: test_basic_init_default_ctx

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def test_basic_init_default_ctx(self):
        ctx_resp = gb.init_sec_context(self.target_name)
        ctx_resp.shouldnt_be_none()

        (ctx, out_mech_type,
         out_req_flags, out_token, out_ttl, cont_needed) = ctx_resp

        ctx.shouldnt_be_none()
        ctx.should_be_a(gb.SecurityContext)

        out_mech_type.should_be(gb.MechType.kerberos)

        out_req_flags.should_be_a(Set)
        out_req_flags.should_be_at_least_length(2)

        out_token.shouldnt_be_empty()

        out_ttl.should_be_greater_than(0)

        cont_needed.should_be_a(bool)

        gb.delete_sec_context(ctx) 
開發者ID:pythongssapi,項目名稱:python-gssapi,代碼行數:24,代碼來源:test_raw.py

示例4: _get_main_qualifier_and_additional_info

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def _get_main_qualifier_and_additional_info(self, arg_value):
        if (isinstance(arg_value, (collections.Set, collections.Sequence)) and
              not isinstance(arg_value, basestring)):
            # the `in_params`/`in_result` field constructor argument is
            # a set or a sequence (but not a string) -- so we expect that
            # it contains the main qualifier (one of VALID_MAIN_QUALIFIERS)
            # and possibly also other items (which we will isolate and place
            # in the `additional_info` frozenset)
            (main_qualifier,
             additional_info) = self._extract_components(arg_value)
        else:
            # otherwise we expect it to be just the main qualifier or None
            # (as in n6sdk)
            if arg_value is not None and arg_value not in VALID_MAIN_QUALIFIERS:
                raise ValueError(
                    "if not None it should be a valid main qualifier "
                    "(one of: {}) or a set/sequence containing it".format(
                        ', '.join(sorted(map(repr, VALID_MAIN_QUALIFIERS)))))
            main_qualifier = arg_value
            additional_info = frozenset()
        assert main_qualifier is None and not additional_info or (
            main_qualifier in VALID_MAIN_QUALIFIERS and
            not (additional_info & VALID_MAIN_QUALIFIERS))
        return main_qualifier, additional_info 
開發者ID:CERT-Polska,項目名稱:n6,代碼行數:26,代碼來源:fields.py

示例5: assertEqualIncludingTypes

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def assertEqualIncludingTypes(self, first, second, msg=None):
        self.assertEqual(first, second)
        if first is not mock.ANY and second is not mock.ANY:
            self.assertIs(type(first), type(second),
                          'type of {!r} ({}) is not type of {!r} ({})'
                          .format(first, type(first), second, type(second)))
        if isinstance(first, collections.Sequence) and not isinstance(first, basestring):
            for val1, val2 in zip(first, second):
                self.assertEqualIncludingTypes(val1, val2)
        elif isinstance(first, collections.Set):
            for val1, val2 in zip(sorted(first, key=self._safe_sort_key),
                                  sorted(second, key=self._safe_sort_key)):
                self.assertEqualIncludingTypes(val1, val2)
        elif isinstance(first, collections.Mapping):
            for key1, key2 in zip(sorted(first.iterkeys(), key=self._safe_sort_key),
                                  sorted(second.iterkeys(), key=self._safe_sort_key)):
                self.assertEqualIncludingTypes(key1, key2)
            for key in first:
                self.assertEqualIncludingTypes(first[key], second[key]) 
開發者ID:CERT-Polska,項目名稱:n6,代碼行數:21,代碼來源:_generic_helpers.py

示例6: objview

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def objview(obj,withValues,path = str()):
    ''' That function will iterate recursivlly accross members of class
        or collections, until all primitives are found '''
    if not len(path): path = type(obj).__name__ 
    iterator = None
    if isinstance(obj, Mapping):
         iterator = iteritems
    else: 
         if isinstance(obj, (Sequence,Set,array.array,deque)) \
            and not isinstance(obj,__string_types__)  and not hasattr(obj,'_asdict'):
            iterator = enumerate
         else: 
            if not type(obj).__name__ in __primitiveTypes__:
               iterator = class__view

    if iterator:
            for path_component, value in iterator(obj):
                valuetype = type(value).__name__ 
                nextpath = path + ('[%s]' % str(path_component)) 
                if (not withValues): yield nextpath, valuetype
                for result in objview(value,withValues,nextpath):               
                    if (withValues or (valuetype not in __primitiveTypes__)):  yield result
    else:
        yield path, obj 
開發者ID:ActiveState,項目名稱:code,代碼行數:26,代碼來源:recipe-578039.py

示例7: traverse_template

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def traverse_template(obj, obj_path=(), memo=None):
    def iteritems(mapping):
        return getattr(mapping, 'iteritems', mapping.items)()

    if memo is None:
        memo = set()
    iterator = None
    if isinstance(obj, Mapping):
        iterator = iteritems
    elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, (str, bytes)):
        iterator = enumerate
    if iterator:
        if id(obj) not in memo:
            memo.add(id(obj))
            for path_component, value in iterator(obj):
                for result in traverse_template(value, obj_path + (path_component,), memo):
                    yield result
            memo.remove(id(obj))
    else:
        yield obj_path, obj 
開發者ID:cfstacks,項目名稱:stacks,代碼行數:22,代碼來源:cf.py

示例8: len_shape_watch

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def len_shape_watch(source, value):
    try:
        shape = value.shape
    except Exception:
        pass
    else:
        if not inspect.ismethod(shape):
            return '{}.shape'.format(source), shape

    if isinstance(value, QuerySet):
        # Getting the length of a Django queryset evaluates it
        return None

    length = len(value)
    if (
            (isinstance(value, six.string_types)
             and length < 50) or
            (isinstance(value, (Mapping, Set, Sequence))
             and length == 0)
    ):
        return None

    return 'len({})'.format(source), length 
開發者ID:alexmojaki,項目名稱:executing,代碼行數:25,代碼來源:configuration.py

示例9: _make_cmp

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def _make_cmp(self, set_op, doc):
        "Make comparator method."
        def comparer(self, that):
            "Compare method for sorted set and set-like object."
            # pylint: disable=protected-access
            if isinstance(that, SortedSet):
                return set_op(self._set, that._set)
            elif isinstance(that, Set):
                return set_op(self._set, that)
            else:
                return NotImplemented

        comparer.__name__ = '__{0}__'.format(set_op.__name__)
        doc_str = 'Return True if and only if Set is {0} `that`.'
        comparer.__doc__ = doc_str.format(doc)

        return comparer 
開發者ID:eirannejad,項目名稱:pyRevit,代碼行數:19,代碼來源:sortedset.py

示例10: default_exit

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def default_exit(path, key, old_parent, new_parent, new_items):
    # print('exit(%r, %r, %r, %r, %r)'
    #       % (path, key, old_parent, new_parent, new_items))
    ret = new_parent
    if isinstance(new_parent, Mapping):
        new_parent.update(new_items)
    elif isinstance(new_parent, Sequence):
        vals = [v for i, v in new_items]
        try:
            new_parent.extend(vals)
        except AttributeError:
            ret = new_parent.__class__(vals)  # tuples
    elif isinstance(new_parent, Set):
        vals = [v for i, v in new_items]
        try:
            new_parent.update(vals)
        except AttributeError:
            ret = new_parent.__class__(vals)  # frozensets
    else:
        raise RuntimeError("unexpected iterable type: %r" % type(new_parent))
    return ret 
開發者ID:HunterMcGushion,項目名稱:hyperparameter_hunter,代碼行數:23,代碼來源:boltons_utils.py

示例11: detect_language

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def detect_language(self, text, languages):
        if isinstance(languages, (list, tuple, Set)):

            if all([language in self.available_language_map for language in languages]):
                languages = [self.available_language_map[language] for language in languages]
            else:
                unsupported_languages = set(languages) - set(self.available_language_map.keys())
                raise ValueError(
                    "Unknown language(s): %s" % ', '.join(map(repr, unsupported_languages)))
        elif languages is not None:
            raise TypeError("languages argument must be a list (%r given)" % type(languages))

        if languages:
            self.language_detector = FullTextLanguageDetector(languages=languages)
        else:
            self.language_detector = FullTextLanguageDetector(list(self.available_language_map.values()))

        return self.language_detector._best_language(text) 
開發者ID:scrapinghub,項目名稱:dateparser,代碼行數:20,代碼來源:search.py

示例12: encode

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def encode(obj):
    if type(obj) in (list, tuple) or isinstance(obj, PVector):
        return [encode(item) for item in obj]
    if isinstance(obj, Mapping):
        encoded_obj = {}
        for key in obj.keys():
            encoded_obj[encode(key)] = encode(obj[key])
        return encoded_obj
    if isinstance(obj, _native_builtin_types):
        return obj
    if isinstance(obj, Set):
        return ExtType(TYPE_PSET, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, PList):
        return ExtType(TYPE_PLIST, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, PBag):
        return ExtType(TYPE_PBAG, packb([encode(item) for item in obj], use_bin_type=True))
    if isinstance(obj, types.FunctionType):
        return ExtType(TYPE_FUNC, encode_func(obj))
    if isinstance(obj, Receiver):
        return ExtType(TYPE_MBOX, packb(obj.encode(), use_bin_type=True))
    # assume record
    cls = obj.__class__
    return ExtType(0, packb([cls.__module__, cls.__name__] + [encode(item) for item in obj],
                            use_bin_type=True)) 
開發者ID:i2y,項目名稱:mochi,代碼行數:26,代碼來源:mailbox.py

示例13: stage

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def stage(obj, parent=None, member=None):
    """
    Prepare obj to be staged.

    This is almost used for relative JSON Pointers.
    """
    obj = Staged(obj, parent, member)

    if isinstance(obj, Mapping):
        for key, value in obj.items():
            stage(value, obj, key)
    elif isinstance(obj, Sequence) and not isinstance(obj, string_types):
        for index, value in enumerate(obj):
            stage(value, obj, index)
    elif isinstance(obj, Set):
        for value in obj:
            stage(value, obj, None)

    return obj 
開發者ID:johnnoone,項目名稱:json-spec,代碼行數:21,代碼來源:stages.py

示例14: __init__

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def __init__(self, viewer, nbunch=None, data=False, default=None):
        self._viewer = viewer
        self._adjdict = viewer._adjdict
        if nbunch is None:
            self._nodes_nbrs = self._adjdict.items
        else:
            nbunch = list(viewer._graph.nbunch_iter(nbunch))
            self._nodes_nbrs = lambda: [(n, self._adjdict[n]) for n in nbunch]
        self._nbunch = nbunch
        self._data = data
        self._default = default
        # Set _report based on data and default
        if data is True:
            self._report = lambda n, nbr, dd: (n, nbr, dd)
        elif data is False:
            self._report = lambda n, nbr, dd: (n, nbr)
        else:  # data is attribute name
            self._report = lambda n, nbr, dd: \
                    (n, nbr, dd[data]) if data in dd else (n, nbr, default) 
開發者ID:aws-samples,項目名稱:aws-kube-codesuite,代碼行數:21,代碼來源:reportviews.py

示例15: __make_cmp

# 需要導入模塊: import collections [as 別名]
# 或者: from collections import Set [as 別名]
def __make_cmp(set_op, symbol, doc):
        "Make comparator method."
        def comparer(self, other):
            "Compare method for sorted set and set."
            if isinstance(other, SortedSet):
                return set_op(self._set, other._set)
            elif isinstance(other, Set):
                return set_op(self._set, other)
            return NotImplemented

        set_op_name = set_op.__name__
        comparer.__name__ = '__{0}__'.format(set_op_name)
        doc_str = """Return true if and only if sorted set is {0} `other`.

        ``ss.__{1}__(other)`` <==> ``ss {2} other``

        Comparisons use subset and superset semantics as with sets.

        Runtime complexity: `O(n)`

        :param other: `other` set
        :return: true if sorted set is {0} `other`

        """
        comparer.__doc__ = dedent(doc_str.format(doc, set_op_name, symbol))
        return comparer 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:28,代碼來源:sortedset.py


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