当前位置: 首页>>代码示例>>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;未经允许,请勿转载。