本文整理汇总了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)
示例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
示例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)
示例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
示例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])
示例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
示例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
示例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
示例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
示例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
示例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)
示例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))
示例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
示例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)
示例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