本文整理汇总了Python中builtins.any方法的典型用法代码示例。如果您正苦于以下问题:Python builtins.any方法的具体用法?Python builtins.any怎么用?Python builtins.any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类builtins
的用法示例。
在下文中一共展示了builtins.any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: control_dependencies
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def control_dependencies(dependencies, graph=None):
"""
Ensure that all `dependencies` are executed before any operations in this scope.
Parameters
----------
dependencies : list
Sequence of operations to be evaluted before evaluating any operations defined in this
scope.
"""
# Add dependencies to the graph
graph = Graph.get_active_graph(graph)
graph.dependencies.extend(dependencies)
yield
# Remove dependencies from the graph
del graph.dependencies[-len(dependencies):]
# pylint: disable=C0103
示例2: count
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def count(iterable):
'''Return the element count of ``iterable``.
This is similar to the built-in :func:`len() <python:len>`, except that it
can also handle any argument that supports iteration, including
generators.
'''
try:
return builtins.len(iterable)
except TypeError:
# Try to determine length by iterating over the iterable
ret = 0
for ret, _ in builtins.enumerate(iterable, start=1):
pass
return ret
示例3: updatelocals
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def updatelocals(self, **vardict):
'''Update variables in the local scope.
This is a shortcut function to inject variables in the local scope
without extensive checks (as in define()). Vardict must not contain any
entries which have been made global via addglobal() before. In order to
ensure this, updatelocals() should be called immediately after
openscope(), or with variable names, which are warrantedly not globals
(e.g variables starting with forbidden prefix)
Args:
**vardict: variable definitions.
'''
self._scope.update(vardict)
if self._locals is not None:
self._locals.update(vardict)
示例4: _quantile_is_valid
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def _quantile_is_valid(q):
# avoid expensive reductions, relevant for arrays with < O(1000) elements
if q.ndim == 1 and q.size < 10:
for i in range(q.size):
if q[i] < 0.0 or q[i] > 1.0:
return False
else:
# faster than any()
if np.count_nonzero(q < 0.0) or np.count_nonzero(q > 1.0):
return False
return True
示例5: any
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def any(iterable):
"""
Returns True if any element of the iterable is true.
"""
for element in iterable:
if element:
return True
return False
示例6: normalize_operation
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def normalize_operation(self, operation): # pylint:disable=W0621
"""
Normalize an operation by resolving its name if necessary.
Parameters
----------
operation : Operation or str
Operation instance or name of an operation.
Returns
-------
normalized_operation : Operation
Operation instance.
Raises
------
ValueError
If `operation` is not an `Operation` instance or an operation name.
RuntimeError
If `operation` is an `Operation` instance but does not belong to this graph.
KeyError
If `operation` is an operation name that does not match any operation of this graph.
"""
if isinstance(operation, Operation):
if operation.graph is not self:
raise RuntimeError(f"operation '{operation}' does not belong to this graph")
return operation
if isinstance(operation, str):
return self.operations[operation]
raise ValueError(f"'{operation}' is not an `Operation` instance or operation name")
示例7: evaluate_operation
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def evaluate_operation(cls, operation, context, **kwargs):
"""
Evaluate an operation or constant given a context.
"""
try:
if isinstance(operation, Operation):
return operation.evaluate(context, **kwargs)
partial = functools.partial(cls.evaluate_operation, context=context, **kwargs)
if isinstance(operation, tuple):
return tuple(partial(element) for element in operation)
if isinstance(operation, list):
return [partial(element) for element in operation]
if isinstance(operation, dict):
return {partial(key): partial(value) for key, value in operation.items()}
if isinstance(operation, slice):
return slice(*[partial(getattr(operation, attr))
for attr in ['start', 'stop', 'step']])
return operation
except Exception as ex: # pragma: no cover
stack = []
interactive = False
for frame in reversed(operation._stack): # pylint: disable=protected-access
# Do not capture any internal stack traces
if 'pythonflow' in frame.filename:
continue
# Stop tracing at the last interactive cell
if interactive and not frame.filename.startswith('<'):
break # pragma: no cover
interactive = frame.filename.startswith('<')
stack.append(frame)
stack = "".join(traceback.format_list(reversed(stack)))
message = "Failed to evaluate operation `%s` defined at:\n\n%s" % (operation, stack)
raise ex from EvaluationError(message)
示例8: any
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def any(iterable):
'''Replacement for the built-in :func:`any() <python:any>` function.'''
return builtins.any(iterable)
示例9: or_
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def or_(a, b):
'''Deferrable version of the :keyword:`or` operator.
:returns: ``a or b``.'''
return builtins.any([a, b])
示例10: extractsingle
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def extractsingle(patt, filename, tag=0, conv=None, item=0, encoding='utf-8'):
'''Extract a single value from the capturing group ``tag`` of a matching
regex ``patt`` in the file ``filename``.
This function is equivalent to ``extractall(patt, filename, tag,
conv)[item]``, except that it raises a ``SanityError`` if ``item`` is out
of bounds.
:arg patt: as in :func:`extractall`.
:arg filename: as in :func:`extractall`.
:arg encoding: as in :func:`extractall`.
:arg tag: as in :func:`extractall`.
:arg conv: as in :func:`extractall`.
:arg item: the specific element to extract.
:returns: The extracted value.
:raises reframe.core.exceptions.SanityError: In case of errors.
'''
try:
# Explicitly evaluate the expression here, so as to force any exception
# to be thrown in this context and not during the evaluation of an
# expression containing this one.
return evaluate(extractall(patt, filename, tag, conv, encoding)[item])
except IndexError:
raise SanityError(
"not enough matches of pattern `%s' in file `%s' "
"so as to extract item `%s'" % (patt, filename, item)
)
# Numeric functions
示例11: getitem
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def getitem(container, item):
'''Get ``item`` from ``container``.
``container`` may refer to any container that can be indexed.
:raises reframe.core.exceptions.SanityError: In case ``item`` cannot be
retrieved from ``container``.
'''
try:
return container[item]
except KeyError:
raise SanityError('key not found: %s' % item)
except IndexError:
raise SanityError('index out of bounds: %s' % item)
示例12: updateglobals
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def updateglobals(self, **vardict):
'''Update variables in the global scope.
This is a shortcut function to inject protected variables in the global
scope without extensive checks (as in define()). Vardict must not
contain any global entries which can be shadowed in local scopes
(e.g. should only contain variables with forbidden prefix).
Args:
**vardict: variable definitions.
'''
self._scope.update(vardict)
if self._locals is not None:
self._globals.update(vardict)
示例13: __call__
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def __call__(self, line):
'''Returns the entire line without any folding.
Returns:
list of str: Components of folded line. They should be
assembled via ``\\n.join()`` to obtain the string
representation.
'''
return [line]
示例14: _get_ufunc_and_otypes
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def _get_ufunc_and_otypes(self, func, args):
"""Return (ufunc, otypes)."""
# frompyfunc will fail if args is empty
if not args:
raise ValueError('args can not be empty')
if self.otypes is not None:
otypes = self.otypes
nout = len(otypes)
# Note logic here: We only *use* self._ufunc if func is self.pyfunc
# even though we set self._ufunc regardless.
if func is self.pyfunc and self._ufunc is not None:
ufunc = self._ufunc
else:
ufunc = self._ufunc = frompyfunc(func, len(args), nout)
else:
# Get number of outputs and output types by calling the function on
# the first entries of args. We also cache the result to prevent
# the subsequent call when the ufunc is evaluated.
# Assumes that ufunc first evaluates the 0th elements in the input
# arrays (the input values are not checked to ensure this)
args = [asarray(arg) for arg in args]
if builtins.any(arg.size == 0 for arg in args):
raise ValueError('cannot call `vectorize` on size 0 inputs '
'unless `otypes` is set')
inputs = [arg.flat[0] for arg in args]
outputs = func(*inputs)
# Performance note: profiling indicates that -- for simple
# functions at least -- this wrapping can almost double the
# execution time.
# Hence we make it optional.
if self.cache:
_cache = [outputs]
def _func(*vargs):
if _cache:
return _cache.pop()
else:
return func(*vargs)
else:
_func = func
if isinstance(outputs, tuple):
nout = len(outputs)
else:
nout = 1
outputs = (outputs,)
otypes = ''.join([asarray(outputs[_k]).dtype.char
for _k in range(nout)])
# Performance note: profiling indicates that creating the ufunc is
# not a significant cost compared with wrapping so it seems not
# worth trying to cache this.
ufunc = frompyfunc(_func, len(args), nout)
return ufunc, otypes
示例15: _median
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import any [as 别名]
def _median(a, axis=None, out=None, overwrite_input=False):
# can't be reasonably be implemented in terms of percentile as we have to
# call mean to not break astropy
a = np.asanyarray(a)
# Set the partition indexes
if axis is None:
sz = a.size
else:
sz = a.shape[axis]
if sz % 2 == 0:
szh = sz // 2
kth = [szh - 1, szh]
else:
kth = [(sz - 1) // 2]
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact):
kth.append(-1)
if overwrite_input:
if axis is None:
part = a.ravel()
part.partition(kth)
else:
a.partition(kth, axis=axis)
part = a
else:
part = partition(a, kth, axis=axis)
if part.shape == ():
# make 0-D arrays work
return part.item()
if axis is None:
axis = 0
indexer = [slice(None)] * part.ndim
index = part.shape[axis] // 2
if part.shape[axis] % 2 == 1:
# index with slice to allow mean (below) to work
indexer[axis] = slice(index, index+1)
else:
indexer[axis] = slice(index-1, index+1)
indexer = tuple(indexer)
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact) and sz > 0:
# warn and return nans like mean would
rout = mean(part[indexer], axis=axis, out=out)
return np.lib.utils._median_nancheck(part, rout, axis, out)
else:
# if there are no nans
# Use mean in odd and even case to coerce data type
# and check, use out array.
return mean(part[indexer], axis=axis, out=out)