本文整理汇总了Python中six.moves.reduce函数的典型用法代码示例。如果您正苦于以下问题:Python reduce函数的具体用法?Python reduce怎么用?Python reduce使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了reduce函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self,proj_id):
self.dtype = np.float32
try:
self.vg = projector.volume_geometry(proj_id)
self.pg = projector.projection_geometry(proj_id)
self.data_mod = data2d
self.appendString = ""
if projector.is_cuda(proj_id):
self.appendString += "_CUDA"
except Exception:
self.vg = projector3d.volume_geometry(proj_id)
self.pg = projector3d.projection_geometry(proj_id)
self.data_mod = data3d
self.appendString = "3D"
if projector3d.is_cuda(proj_id):
self.appendString += "_CUDA"
self.vshape = functions.geom_size(self.vg)
self.vsize = reduce(operator.mul,self.vshape)
self.sshape = functions.geom_size(self.pg)
self.ssize = reduce(operator.mul,self.sshape)
self.shape = (self.ssize, self.vsize)
self.proj_id = proj_id
self.T = OpTomoTranspose(self)
开发者ID:eureka3,项目名称:astra-toolbox,代码行数:27,代码来源:optomo.py
示例2: _get_merged_histograms
def _get_merged_histograms(cursor, property_name, path, with_processes,
histograms_url, additional_histograms):
if path[0] == "histograms" and len(path) != 2:
raise ValueError("Histogram access requires a histogram name.")
elif path[0] == "keyedHistograms" and len(path) != 3:
raise ValueError("Keyed histogram access requires both a histogram name and a label.")
# Get parent property
parent = _get_ping_property(cursor, path, histograms_url,
additional_histograms)
# Get children properties
if not isinstance(cursor, dict):
children = []
else:
children = [_get_ping_property(cursor["processes"]["content"],
path, histograms_url,
additional_histograms)]
children += [_get_ping_property(child, path, histograms_url, additional_histograms)
for child in cursor.get("childPayloads", [])]
children += [_get_ping_property(cursor["processes"]["gpu"],
path, histograms_url,
additional_histograms)]
children = list(filter(lambda h: h is not None, children))
# Merge parent and children
merged = ([parent] if parent else []) + children
result = {}
if with_processes:
result[property_name + "_parent"] = parent
result[property_name + "_children"] = reduce(add, children) if children else None
result[property_name] = reduce(add, merged) if merged else None
return result
开发者ID:mozilla,项目名称:python_moztelemetry,代码行数:35,代码来源:spark.py
示例3: generate
def generate(operator, *args):
"""Generates SparseInterval instance current and past
results of RecurrentEvent.forward() generators with respect
to 'operator' of given expression."""
operands = []
for arg in args:
if isinstance(arg, dict):
try:
result = next(arg['generator'])
arg['results'] = (
arg['results'].union(SparseInterval(*[result]))
)
except StopIteration:
arg['exhausted'] = True
operands.append(arg['results'])
elif isinstance(arg, SparseInterval):
operands.append(arg)
if operator == AND:
return reduce(lambda m, v: m.intersection(v), operands)
elif operator == OR:
return reduce(lambda m, v: m.union(v), operands)
elif operator == NOT:
union = reduce(lambda m, v: m.union(v), operands)
intervals = it.chain((MIN,),
it.chain.from_iterable(union.intervals),
(MAX,))
return SparseInterval(*zip(intervals, intervals))
else:
raise AssertionError
开发者ID:AndrewPashkin,项目名称:python-tempo,代码行数:29,代码来源:recurrenteventset.py
示例4: reshape
def reshape(self, *shape):
"""Gives a new shape to an array without changing its data."""
# TODO: add more error-checking, perhaps
if not self.flags.forc:
raise RuntimeError("only contiguous arrays may "
"be used as arguments to this operation")
if isinstance(shape[0], tuple) or isinstance(shape[0], list):
shape = tuple(shape[0])
if shape == self.shape:
return self
if -1 in shape:
shape = list(shape)
idx = shape.index(-1)
size = -reduce(lambda x, y: x * y, shape, 1)
shape[idx] = self.size // size
if -1 in shape[idx:]:
raise ValueError("can only specify one unknown dimension")
shape = tuple(shape)
size = reduce(lambda x, y: x * y, shape, 1)
if size != self.size:
raise ValueError("total size of new array must be unchanged")
return GPUArray(
shape=shape,
dtype=self.dtype,
allocator=self.allocator,
base=self,
gpudata=int(self.gpudata))
开发者ID:Benli11,项目名称:pycuda,代码行数:33,代码来源:gpuarray.py
示例5: backtrack
def backtrack(self, node, tasks):
candidates = self.fetch_tracks(node.op)
tracks = []
def filter(node, depth):
new_candidates = []
for candidate in candidates:
track, i, lopt = candidate
if i < depth:
pass
elif track[i-depth] in (None, node.op):
if i == depth:
tasks[node].append(lopt)
else:
tracks.append(candidate)
else:
new_candidates.append(candidate)
return new_candidates
depth = 0
nodes = [node]
while candidates:
for node in nodes:
candidates = list(filter(node, depth))
depth += 1
_nodes = nodes
nodes = reduce(list.__iadd__,
[reduce(list.__iadd__,
[[n for n, i in out.clients if not isinstance(n, string_types)] for out in node.outputs],
[]) for node in nodes],
[])
candidates = tracks
tracks = []
开发者ID:5730279821-TA,项目名称:Theano,代码行数:31,代码来源:equilibrium.py
示例6: get_context_data
def get_context_data(self, **kwargs):
context = super(SearchableListMixin, self).get_context_data(**kwargs)
qs = self.model.objects.all()
total_objects = qs.count()
query = self.get_search_query()
is_filter = False
if query:
is_filter = True
w_qs = []
search_pairs = self.get_search_fields_with_filters()
for word in self.get_words(query):
filters = [Q(**{'%s__%s' % (pair[0], pair[1]): word}) for pair in search_pairs]
if self.search_date_fields:
dt = self.try_convert_to_date(word)
if dt:
filters.extend([Q(**{field_name: dt}) for field_name in self.search_date_fields])
w_qs.append(reduce(operator.or_, filters))
qs = qs.filter(reduce(operator.and_, w_qs))
qs = qs.distinct()
total_objects = qs.count()
paginator = Paginator(qs, 10)
page = self.request.GET.get('page')
try:
qs = paginator.page(page)
except PageNotAnInteger:
qs = paginator.page(1)
except EmptyPage:
qs = paginator.page(paginator.num_pages)
context.update({'object_list': qs, 'is_filter': is_filter, 'total_objects': total_objects})
return context
开发者ID:fcoramirezz,项目名称:gestion_funeraria,代码行数:30,代码来源:mixins.py
示例7: __purity
def __purity(cls, mem, references, macro=True, verbose=False):
clusters = {}
avg = 0
memberships = [x for x in mem]
for (i, x) in memberships:
if x in clusters:
clusters[x].append(i)
else:
clusters[x] = [i]
for docs in clusters.values():
(_, count) = median(reduce(lambda s, x: s + x, [references[x] for x in docs]))
if verbose:
print('# %f = %d/%d, labels %s for cluster %s' % (
float(count) / float(len(docs)),
count, len(docs),
str(reduce(lambda s, x: s + x, [references[x] for x in docs])),
str(docs)))
if macro:
avg += count
else:
avg += float(count) / float(len(docs))
if macro:
return float(avg) / len(memberships)
else:
return float(avg) / len(clusters)
开发者ID:whym,项目名称:scluster,代码行数:25,代码来源:evaluate.py
示例8: as_list
def as_list(self):
# on top-level, I have type and depth, for easier parallelism,
# but this is hacky as hell
schema = (
self.schema.items if isinstance(self.schema, ArraySchema)
else self.schema
)
items = [InputAdapter(item, self.evaluator, schema)
for item in self.value]
if not self.prefix:
return reduce(operator.add, [a.arg_list() for a in items], [])
if self.separate and self.item_separator is None:
return reduce(operator.add, [[self.prefix] + a.arg_list()
for a in items], [])
if not self.separate and self.item_separator is None:
return [self.prefix + a.list_item()
for a in items if a.list_item() is not None]
joined = self.item_separator.join(
filter(None, [a.list_item() for a in items])
)
if self.separate and self.item_separator is not None:
return [self.prefix, joined]
return [self.prefix + joined]
开发者ID:lowks,项目名称:rabix,代码行数:28,代码来源:adapter.py
示例9: evaluate
def evaluate(self, previousResult, original=None, fast=False):
original = original if original is not None else previousResult
if original._grouped_self and fast:
name = GetName(self)
# TODO: Rewrite this, this is terrible.
go_to_index = len(self._queue)
for idx, item in enumerate(self._queue):
if isinstance(item, OperatorStep):
go_to_index = idx
break
transform_input = lambda x: reduce(
lambda prevResult, f: f.evaluate(prevResult, original, fast=fast),
self._queue[1:go_to_index],
x
)
out = original._grouped_self[name].transform(transform_input)
out = reduce(lambda prevResult, f: f.evaluate(prevResult, original, fast=fast),
self._queue[go_to_index:],
out)
return out
else:
output = reduce(lambda prevResult, f: f.evaluate(prevResult, original),
self._queue,
original)
return output
开发者ID:phdkiran,项目名称:dplython,代码行数:28,代码来源:later.py
示例10: __init__
def __init__(self,proj_id):
self.dtype = np.float32
try:
self.vg = projector.volume_geometry(proj_id)
self.pg = projector.projection_geometry(proj_id)
self.data_mod = data2d
self.appendString = ""
if projector.is_cuda(proj_id):
self.appendString += "_CUDA"
except Exception:
self.vg = projector3d.volume_geometry(proj_id)
self.pg = projector3d.projection_geometry(proj_id)
self.data_mod = data3d
self.appendString = "3D"
if projector3d.is_cuda(proj_id):
self.appendString += "_CUDA"
self.vshape = functions.geom_size(self.vg)
self.vsize = reduce(operator.mul,self.vshape)
self.sshape = functions.geom_size(self.pg)
self.ssize = reduce(operator.mul,self.sshape)
self.shape = (self.ssize, self.vsize)
self.proj_id = proj_id
self.transposeOpTomo = OpTomoTranspose(self)
try:
self.T = self.transposeOpTomo
except AttributeError:
# Scipy >= 0.16 defines self.T using self._transpose()
pass
开发者ID:PhysikerErlangen,项目名称:astra-toolbox,代码行数:32,代码来源:optomo.py
示例11: combineQualities
def combineQualities(allowed_qualities, preferred_qualities):
any_quality = 0
best_quality = 0
if allowed_qualities:
any_quality = reduce(operator.or_, allowed_qualities)
if preferred_qualities:
best_quality = reduce(operator.or_, preferred_qualities)
return any_quality | (best_quality << 16)
开发者ID:murbaniak,项目名称:SickRage,代码行数:8,代码来源:common.py
示例12: get_usage
def get_usage(self, using="short"):
if using not in set(["short", "long", "both"]):
raise ValueError(
"using has to be 'short', 'long' or 'both'; not %r" % using
)
# The usage is generated in three steps:
# 1. A "linked list" is generated with lists as nodes. Each node is a
# list consisting of an optional positional as first item followed by
# zero or more required positionals, optionally followed by a list
# representing the next node.
#
# 2. The usage string is generated by enclosing the with a space joined
# usage strings of the positionals in a given node with brackets.
# The exception is the root which is not enclosed by brackets as the
# first node is always required.
#
# 3. The usage string generated in `2` is prefixed with the short and/
# or the long and either or both joined with a comma are returned.
def step(acc, next):
root, current = acc
if next.optional:
current.append([next])
current = current[-1]
else:
current.append(next)
return root, current
def render(tree, _root=True):
if isinstance(tree, Positional):
return tree.usage
else:
nodes = u(" ").join(render(node, _root=False) for node in tree)
if _root:
return nodes
return u("[{0}]").format(nodes)
usage = render(reduce(step, self.positionals, ([], ) * 2)[0])
if using == "both" and self.short and self.long:
return (
u("{0} {1}").format(self.short, usage).strip() +
u(", ") +
u("{0} {1}").format(self.long, usage).strip()
)
else:
return u("{0} {{0}}").format(
self.short if using == "short" and self.short or
using in set(["long", "both"]) and not self.long
else self.long
).format(usage)
return usage.format(
short=self.short,
long=self.long,
usage=render(reduce(step, self.positionals, ([], ) * 2)[0])
).strip()
开发者ID:DasIch,项目名称:awwparse,代码行数:56,代码来源:__init__.py
示例13: lcm
def lcm( *a ):
"""Least common multiple.
Usage: lcm( [ 3, 4, 5 ] )
or: lcm( 3, 4, 5 )
"""
if len( a ) > 1: return reduce( lcm2, a )
if hasattr( a[0], "__iter__" ): return reduce( lcm2, a[0] )
return a[0]
开发者ID:marchon,项目名称:py-ECDSA,代码行数:10,代码来源:numbertheory.py
示例14: gcd
def gcd( *a ):
"""Greatest common divisor.
Usage: gcd( [ 2, 4, 6 ] )
or: gcd( 2, 4, 6 )
"""
if len( a ) > 1: return reduce( gcd2, a )
if hasattr( a[0], "__iter__" ): return reduce( gcd2, a[0] )
return a[0]
开发者ID:marchon,项目名称:py-ECDSA,代码行数:10,代码来源:numbertheory.py
示例15: __setattr__
def __setattr__(self, name, value):
if isinstance(self._parent, Style.Style):
setattr(
reduce(getattr, self._attribute.split('.'), self._parent),
name, value)
else:
for cell in self._parent:
setattr(
reduce(getattr, self._attribute.split('.'), cell),
name, value)
开发者ID:kz26,项目名称:PyExcelerate,代码行数:10,代码来源:Range.py
示例16: expr
def expr(cls):
e = pp.Literal("@").suppress() + v_integer
u = reduce(operator.or_, [pp.Literal(i) for i in human.SIZE_UNITS.keys()]).leaveWhitespace()
e = e + pp.Optional(u, default=None)
s = pp.Literal(",").suppress()
s += reduce(operator.or_, [pp.Literal(i) for i in generators.DATATYPES.keys()])
e += pp.Optional(s, default="bytes")
return e.setParseAction(lambda x: cls(*x))
开发者ID:ollie314,项目名称:mitmproxy,代码行数:10,代码来源:base.py
示例17: _get_total_hits
def _get_total_hits(self):
""" Returns the total number of hits across all teams and players.
"""
return sm.reduce(
add,
[
sm.reduce(add, [p.hits for p in t.players], 0)
for t in self.model.teams
],
0,
)
开发者ID:enthought,项目名称:traits,代码行数:11,代码来源:properties.py
示例18: add_trading_days
def add_trading_days(self, n, date):
if n > 0:
return reduce(
lambda a, b: self.next_trading_day(a),
range(n),
date,
)
else:
return reduce(
lambda a, b: self.previous_trading_day(a),
range(abs(n)),
date,
)
开发者ID:sathoro,项目名称:zipline,代码行数:13,代码来源:trading.py
示例19: flatten
def flatten(s):
if isinstance(s, (tuple, list)):
return reduce(lambda a, b: a + flatten(b), s, [])
elif isinstance(s, set):
raise TypeError("parameter flattening cannot order sets")
elif isinstance(s, dict):
return reduce(lambda a, b: a + flatten(s[b]), sorted(s.keys()), [])
elif isinstance(s, BaseParameter):
return [s]
elif s is None:
return []
else:
raise TypeError("don't understand type %s for %r" % (type(s), s))
开发者ID:jvstealer99,项目名称:bumps,代码行数:13,代码来源:parameter.py
示例20: get_queryset
def get_queryset(self):
qs = super(SearchableListMixin, self).get_queryset()
query = self.get_search_query()
if query:
w_qs = []
search_pairs = self.get_search_fields_with_filters()
for word in self.get_words(query):
filters = [Q(**{'%s__%s' % (pair[0], pair[1]): word}) for pair in search_pairs]
if self.search_date_fields:
dt = self.try_convert_to_date(word)
if dt:
filters.extend([Q(**{field_name: dt}) for field_name in self.search_date_fields])
w_qs.append(reduce(operator.or_, filters))
qs = qs.filter(reduce(operator.and_, w_qs))
return qs.distinct()
开发者ID:AaronJaramillo,项目名称:shopDPM,代码行数:15,代码来源:mixins.py
注:本文中的six.moves.reduce函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论