本文整理汇总了Python中collections.abc.Sequence方法的典型用法代码示例。如果您正苦于以下问题:Python abc.Sequence方法的具体用法?Python abc.Sequence怎么用?Python abc.Sequence使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.abc
的用法示例。
在下文中一共展示了abc.Sequence方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_test
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def run_test(work_type: FunctionType, job_sets: Sequence, trials: int,
pool_class: type, worker_count: int) -> Mapping:
pool = pool_class(worker_count)
if work_type == 'compute':
test_func = pool.run_compute_test
elif work_type == 'network':
test_func = pool.run_network_test
else:
raise Exception("Invalid work type: {}".format(work_type))
results = map(
lambda jobs: test_func(jobs, trials, show_progress=True),
tqdm(job_sets, desc=pool_class.__name__),
)
summarized_results = list(map(summarize_test, results))
pool.destroy_pool()
return summarized_results
示例2: to_tensor
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
:class:`Sequence`, :class:`int` and :class:`float`.
Args:
data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to
be converted.
"""
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)
elif isinstance(data, Sequence) and not mmcv.is_str(data):
return torch.tensor(data)
elif isinstance(data, int):
return torch.LongTensor([data])
elif isinstance(data, float):
return torch.FloatTensor([data])
else:
raise TypeError(f'type {type(data)} cannot be converted to tensor.')
示例3: set_recall_param
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def set_recall_param(proposal_nums, iou_thrs):
"""Check proposal_nums and iou_thrs and set correct format."""
if isinstance(proposal_nums, Sequence):
_proposal_nums = np.array(proposal_nums)
elif isinstance(proposal_nums, int):
_proposal_nums = np.array([proposal_nums])
else:
_proposal_nums = proposal_nums
if iou_thrs is None:
_iou_thrs = np.array([0.5])
elif isinstance(iou_thrs, Sequence):
_iou_thrs = np.array(iou_thrs)
elif isinstance(iou_thrs, float):
_iou_thrs = np.array([iou_thrs])
else:
_iou_thrs = iou_thrs
return _proposal_nums, _iou_thrs
示例4: _check_store_fields
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def _check_store_fields(node, fields, ids, result):
if node.name is not None:
assert ids is not None
if (
isinstance(result, Sequence)
and len(result) == len(ids)
and all(isinstance(r, Sequence) and len(r) == len(fields)
for r in result)
):
return
else:
expected = ('list (len: {}) of lists (len: {})'
.format(len(ids), len(fields)))
else:
if isinstance(result, Sequence) and len(result) == len(fields):
return
else:
expected = 'list (len: {})'.format(len(fields))
raise TypeError('Can\'t store field values, node: {!r}, fields: {!r}, '
'expected: {}, returned: {!r}'
.format(node.name or '__root__', [f.name for f in fields],
expected, result))
示例5: __init__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def __init__(self, x, y, z):
if isinstance(x, (Sequence, np.ndarray)):
raise TypeError("x must be a scalar, not %s." % (type(x)))
if isinstance(y, (Sequence, np.ndarray)):
raise TypeError("y must be a scalar, not %s." % type(y))
if isinstance(z, (Sequence, np.ndarray)):
raise TypeError("z must be a scalar, not %s." % type(z))
self.x = x
self.y = y
self.z = z
# A matplotlib.patches object (e.g., Circle, Rectangle) that can be
# used to plot the electrode:
self.plot_patch = None
# Any keyword arguments that should be passed to the call above:
# (e.g., {'radius': 5}):
self.plot_kwargs = {}
示例6: _path_exists
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def _path_exists(self, operator, condition, entry):
keys_list = list(operator.split('.'))
for i, k in enumerate(keys_list):
if isinstance(entry, Sequence) and not k.isdigit():
for elem in entry:
operator = '.'.join(keys_list[i:])
if self._path_exists(operator, condition, elem) == condition:
return condition
return not condition
elif isinstance(entry, Sequence):
k = int(k)
try:
entry = entry[k]
except (TypeError, IndexError, KeyError):
return not condition
return condition
示例7: _checkout
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def _checkout(self, item):
if isinstance(item, container_abcs.Mapping):
flag = True
for key in item.keys():
flag = flag and self._checkout(item[key])
return flag
if isinstance(item, container_abcs.Sequence):
flag = True
for val in item:
flag = flag and self._checkout(val)
return flag
if isinstance(item, (np.ndarray)):
if item.size > 1:
return False
else:
return True
if isinstance(item, (numbers.Number)):
return True
示例8: always_reversible
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def always_reversible(iterable):
"""An extension of :func:`reversed` that supports all iterables, not
just those which implement the ``Reversible`` or ``Sequence`` protocols.
>>> print(*always_reversible(x for x in range(3)))
2 1 0
If the iterable is already reversible, this function returns the
result of :func:`reversed()`. If the iterable is not reversible,
this function will cache the remaining items in the iterable and
yield them in reverse order, which may require significant storage.
"""
try:
return reversed(iterable)
except TypeError:
return reversed(list(iterable))
示例9: is_seq_of
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def is_seq_of(seq, expected_type, seq_type=None):
"""Check whether it is a sequence of some type.
Args:
seq (Sequence): The sequence to be checked.
expected_type (type): Expected type of sequence items.
seq_type (type, optional): Expected sequence type.
Returns:
bool: Whether the sequence is valid.
"""
if seq_type is None:
exp_seq_type = collections_abc.Sequence
else:
assert isinstance(seq_type, type)
exp_seq_type = seq_type
if not isinstance(seq, exp_seq_type):
return False
for item in seq:
if not isinstance(item, expected_type):
return False
return True
示例10: __or__
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def __or__(self, reg):
"""Apply the operation to a part of a quantum register.
Appends the Operation to a :class:`.Program` instance.
Args:
reg (RegRef, Sequence[RegRef]): subsystem(s) the operation is acting on
Returns:
list[RegRef]: subsystem list as RegRefs
"""
# into a list of subsystems
reg = _seq_to_list(reg)
if (not reg) or (self.ns is not None and self.ns != len(reg)):
raise ValueError("Wrong number of subsystems.")
# append it to the Program
reg = pu.Program_current_context.append(self, reg)
return reg
示例11: isolation_window
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def isolation_window(self, value):
if isinstance(value, IsolationWindow) or value is None:
self._isolation_window = value
elif isinstance(value, Sequence):
if len(value) == 2:
lo, hi = value
width = (hi - lo) / 2.
center = lo + width
self._isolation_window = IsolationWindow(center, width, width)
elif len(value) == 3:
lo, center, hi = value
self._isolation_window = IsolationWindow(lo, center, hi)
else:
raise ValueError("Could not convert %r to an %r" %
(value, IsolationWindow))
else:
raise TypeError(
"isolation_window must be an either an %r instance or a sequence of two or three elements" % (
IsolationWindow))
示例12: _resolve
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def _resolve(self, key):
if key in self.mapping:
return self.mapping[key]
for k, v in self.mapping.items():
if not isinstance(k, Sequence):
continue
if key in k:
return v
best_substr = None
best_substr_len = -1
if not isinstance(key, Sequence):
raise KeyError(key)
for k, v in self.mapping.items():
if k in key:
substr_len = len(k)
if substr_len > best_substr_len:
best_substr = k
best_substr_len = substr_len
if best_substr_len > 0:
return self.mapping[best_substr]
raise KeyError(key)
示例13: map
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def map(self, work_func: FunctionType, inputs: Sequence) -> Sequence:
raise NotImplementedError("{} does not implement map"
.format(self.__class__.__name__))
示例14: is_sequence_container
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def is_sequence_container(obj):
return not isinstance(obj, str) and isinstance(obj, Sequence)
示例15: _check_store_links
# 需要导入模块: from collections import abc [as 别名]
# 或者: from collections.abc import Sequence [as 别名]
def _check_store_links(node, link, ids, result):
if node.name is not None and link.requires is not None:
assert ids is not None
if link.type_enum is Maybe or link.type_enum is One:
if isinstance(result, Sequence) and len(result) == len(ids):
return
else:
expected = 'list (len: {})'.format(len(ids))
elif link.type_enum is Many:
if (
isinstance(result, Sequence)
and len(result) == len(ids)
and all(isinstance(r, Sequence) for r in result)
):
return
else:
expected = 'list (len: {}) of lists'.format(len(ids))
else:
raise TypeError(link.type_enum)
else:
if link.type_enum is Maybe or link.type_enum is One:
return
elif link.type_enum is Many:
if isinstance(result, Sequence):
return
else:
expected = 'list'
else:
raise TypeError(link.type_enum)
raise TypeError('Can\'t store link values, node: {!r}, link: {!r}, '
'expected: {}, returned: {!r}'
.format(node.name or '__root__', link.name,
expected, result))