本文整理匯總了Python中typing.Sized方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Sized方法的具體用法?Python typing.Sized怎麽用?Python typing.Sized使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.Sized方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: zip_equal
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def zip_equal(*args: Union[Sized, Iterable]) -> Iterable[Tuple]:
"""
zip over the given iterables, but enforce that all of them exhaust simultaneously.
Examples
--------
>>> zip_equal([1, 2, 3], [4, 5, 6]) # ok
>>> zip_equal([1, 2, 3], [4, 5, 6, 7]) # raises ValueError
# ValueError is raised even if the lengths are not known
>>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6])) # ok
>>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6, 7])) # raises ValueError
"""
if not args:
return
lengths = []
all_lengths = []
for arg in args:
try:
lengths.append(len(arg))
all_lengths.append(len(arg))
except TypeError:
all_lengths.append('?')
if lengths and not all(x == lengths[0] for x in lengths):
from .checks import join
raise ValueError(f'The arguments have different lengths: {join(all_lengths)}.')
iterables = [iter(arg) for arg in args]
while True:
result = []
for it in iterables:
with suppress(StopIteration):
result.append(next(it))
if len(result) != len(args):
break
yield tuple(result)
if len(result) != 0:
raise ValueError(f'The iterables did not exhaust simultaneously.')
示例2: test_sized
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def test_sized(self):
assert isinstance([], typing.Sized)
assert not isinstance(42, typing.Sized)
示例3: predict_batch
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
"""
Returns a vector of actions chosen at random.
:param observations: Represents a vector of observations. Only used in determining the size
of the returned array.
:return: Numpy array containing the action chosen for each observation.
"""
if not self.use_block:
return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
self._i += 1
return self.noise[: len(observations), self._i % self.samples]
示例4: serialize
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def serialize(self, instance: Sized):
_check_type_and_size(instance, self.actual_type, len(self.items), SerializationError)
return self.actual_type(serialize(o, t) for t, o in zip(self.items, instance))
示例5: contains
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def contains(self, x):
if not isinstance(x, Sized):
return False
if not (self.min_seq_length <= len(x) <= self.max_seq_length):
return False
return all([self.space.contains(el) for el in x])
示例6: are_none
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def are_none(sequences: Sequence[Sized]) -> bool:
"""
Returns True if all sequences are None.
"""
if not sequences:
return True
return all(s is None for s in sequences)
示例7: are_token_parallel
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
"""
Returns True if all sequences in the list have the same length.
"""
if not sequences or len(sequences) == 1:
return True
return all(len(s) == len(sequences[0]) for s in sequences)
示例8: test_sized
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def test_sized(self):
self.assertIsInstance([], typing.Sized)
self.assertNotIsInstance(42, typing.Sized)
示例9: _get_all_dimensions
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def _get_all_dimensions(batch: Sequence, level: int = 0, res: Optional[List[List[int]]] = None) -> List[List[int]]:
"""Return all presented element sizes of each dimension.
Args:
batch: Data array.
level: Recursion level.
res: List containing element sizes of each dimension.
Return:
List, i-th element of which is list containing all presented sized of batch's i-th dimension.
Examples:
>>> x = [[[1], [2, 3]], [[4], [5, 6, 7], [8, 9]]]
>>> _get_all_dimensions(x)
[[2], [2, 3], [1, 2, 1, 3, 2]]
"""
if not level:
res = [[len(batch)]]
if len(batch) and isinstance(batch[0], Sized) and not isinstance(batch[0], str):
level += 1
if len(res) <= level:
res.append([])
for item in batch:
res[level].append(len(item))
_get_all_dimensions(item, level, res)
return res
示例10: from_parameters
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def from_parameters(cls, parameters: Sequence[float]) -> Sized:
"""Construct Robot from Kinematic Chain parameters."""
# FIXME: assumes MDH revolute robot
kc = MDHKinematicChain.from_parameters(parameters)
return cls(kinematic_chain=kc)
示例11: predict_batch
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
"""
Returns a vector of actions chosen at random.
:param observations: Represents a vector of observations. Only used in determining the size
of the returned array.
:return: Numpy array containing the action chosen for each observation.
"""
if not self.use_block:
return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
self._i += 1
return self.noise[:len(observations), self._i % self.samples]
示例12: _count_values
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def _count_values(dictionary: Dict[str, Sized]) -> int:
return sum(len(e) for e in dictionary.values())
示例13: plot_assignments
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Sized [as 別名]
def plot_assignments(
assignments: torch.Tensor,
im: Optional[AxesImage] = None,
figsize: Tuple[int, int] = (5, 5),
classes: Optional[Sized] = None,
) -> AxesImage:
# language=rst
"""
Plot the two-dimensional neuron assignments.
:param assignments: Vector of neuron label assignments.
:param im: Used for re-drawing the assignments plot.
:param figsize: Horizontal, vertical figure size in inches.
:param classes: Iterable of labels for colorbar ticks corresponding to data labels.
:return: Used for re-drawing the assigments plot.
"""
locals_assignments = assignments.detach().clone().cpu().numpy()
if not im:
fig, ax = plt.subplots(figsize=figsize)
ax.set_title("Categorical assignments")
if classes is None:
color = plt.get_cmap("RdBu", 11)
im = ax.matshow(
locals_assignments, cmap=color, vmin=-1.5, vmax=9.5
)
else:
color = plt.get_cmap("RdBu", len(classes) + 1)
im = ax.matshow(
locals_assignments,
cmap=color,
vmin=-1.5,
vmax=len(classes) - 0.5,
)
div = make_axes_locatable(ax)
cax = div.append_axes("right", size="5%", pad=0.05)
if classes is None:
cbar = plt.colorbar(im, cax=cax, ticks=list(range(-1, 11)))
cbar.ax.set_yticklabels(["none"] + list(range(10)))
else:
cbar = plt.colorbar(im, cax=cax, ticks=np.arange(-1, len(classes)))
cbar.ax.set_yticklabels(["none"] + list(classes))
ax.set_xticks(())
ax.set_yticks(())
fig.tight_layout()
else:
im.set_data(locals_assignments)
return im