本文整理匯總了Python中itertools.ifilter方法的典型用法代碼示例。如果您正苦於以下問題:Python itertools.ifilter方法的具體用法?Python itertools.ifilter怎麽用?Python itertools.ifilter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類itertools
的用法示例。
在下文中一共展示了itertools.ifilter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __and__
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def __and__(self, other):
''' Intersection is the minimum of corresponding counts.
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
_min = min
result = Counter()
if len(self) < len(other):
self, other = other, self
for elem in ifilter(self.__contains__, other):
newcount = _min(self[elem], other[elem])
if newcount > 0:
result[elem] = newcount
return result
示例2: wallclock_for_operation
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def wallclock_for_operation(results, operation):
"""
Calculate the wallclock time for a process running in a particular
scenario.
:param results: Results to extract values from.
:param operation: Operation name to calculate wallclock results for.
:return: The mean wallclock time observed.
"""
operation_results = itertools.ifilter(
lambda r: r['metric']['type'] == 'wallclock' and
r['operation']['type'] == operation,
results
)
values = [r['value'] for r in operation_results]
return mean(values)
示例3: __and__
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def __and__(self, other):
''' Intersection is the minimum of corresponding counts.
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
_min = min
result = Counter()
if len(self) < len(other):
self, other = other, self
for elem in ifilter(self.__contains__, other):
newcount = _min(self[elem], other[elem])
if newcount > 0:
result[elem] = newcount
return result
示例4: countByValueAndWindow
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def countByValueAndWindow(self, windowDuration, slideDuration, numPartitions=None):
"""
Return a new DStream in which each RDD contains the count of distinct elements in
RDDs in a sliding window over this DStream.
@param windowDuration: width of the window; must be a multiple of this DStream's
batching interval
@param slideDuration: sliding interval of the window (i.e., the interval after which
the new DStream will generate RDDs); must be a multiple of this
DStream's batching interval
@param numPartitions: number of partitions of each RDD in the new DStream.
"""
keyed = self.map(lambda x: (x, 1))
counted = keyed.reduceByKeyAndWindow(operator.add, operator.sub,
windowDuration, slideDuration, numPartitions)
return counted.filter(lambda kv: kv[1] > 0)
示例5: lookup
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def lookup(self, key):
"""
Return the list of values in the RDD for key `key`. This operation
is done efficiently if the RDD has a known partitioner by only
searching the partition that the key maps to.
>>> l = range(1000)
>>> rdd = sc.parallelize(zip(l, l), 10)
>>> rdd.lookup(42) # slow
[42]
>>> sorted = rdd.sortByKey()
>>> sorted.lookup(42) # fast
[42]
>>> sorted.lookup(1024)
[]
>>> rdd2 = sc.parallelize([(('a', 'b'), 'c')]).groupByKey()
>>> list(rdd2.lookup(('a', 'b'))[0])
['c']
"""
values = self.filter(lambda kv: kv[0] == key).values()
if self.partitioner is not None:
return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)])
return values.collect()
示例6: __define_optimizer
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def __define_optimizer(self, learning_rate, weight_decay,
lr_drop_factor, lr_drop_patience, optimizer='Adam'):
assert optimizer in ['RMSprop', 'Adam', 'Adadelta', 'SGD']
parameters = ifilter(lambda p: p.requires_grad,
self.model.parameters())
if optimizer == 'RMSprop':
self.optimizer = optim.RMSprop(
parameters, lr=learning_rate, weight_decay=weight_decay)
elif optimizer == 'Adadelta':
self.optimizer = optim.Adadelta(
parameters, lr=learning_rate, weight_decay=weight_decay)
elif optimizer == 'Adam':
self.optimizer = optim.Adam(
parameters, lr=learning_rate, weight_decay=weight_decay)
elif optimizer == 'SGD':
self.optimizer = optim.SGD(
parameters, lr=learning_rate, momentum=0.9,
weight_decay=weight_decay)
self.lr_scheduler = ReduceLROnPlateau(
self.optimizer, mode='min', factor=lr_drop_factor,
patience=lr_drop_patience, verbose=True)
示例7: iteritems
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def iteritems(self):
definitions = type(self).configuration_setting_definitions
version = self.command.protocol_version
return ifilter(
lambda (name, value): value is not None, imap(
lambda setting: (setting.name, setting.__get__(self)), ifilter(
lambda setting: setting.is_supported_by_protocol(version), definitions)))
示例8: iteritems
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def iteritems(self):
iteritems = SearchCommand.ConfigurationSettings.iteritems(self)
version = self.command.protocol_version
if version == 1:
if self.required_fields is None:
iteritems = ifilter(lambda (name, value): name != 'clear_required_fields', iteritems)
else:
iteritems = ifilter(lambda (name, value): name != 'distributed', iteritems)
if self.distributed:
iteritems = imap(
lambda (name, value): (name, 'stateful') if name == 'type' else (name, value), iteritems)
return iteritems
# endregion
示例9: iteritems
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def iteritems(self):
iteritems = SearchCommand.ConfigurationSettings.iteritems(self)
version = self.command.protocol_version
if version == 2:
iteritems = ifilter(lambda (name, value): name != 'distributed', iteritems)
if self.distributed and self.type == 'streaming':
iteritems = imap(
lambda (name, value): (name, 'stateful') if name == 'type' else (name, value), iteritems)
return iteritems
示例10: _compile_object
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def _compile_object(self, schema):
"""Validate an object.
Has the same behavior as dictionary validator but work with object
attributes.
For example:
>>> class Structure(object):
... def __init__(self, one=None, three=None):
... self.one = one
... self.three = three
...
>>> validate = Schema(Object({'one': 'two', 'three': 'four'}, cls=Structure))
>>> with raises(MultipleInvalid, "not a valid value for object value @ data['one']"):
... validate(Structure(one='three'))
"""
base_validate = self._compile_mapping(
schema, invalid_msg='object value')
def validate_object(path, data):
if (schema.cls is not UNDEFINED
and not isinstance(data, schema.cls)):
raise ObjectInvalid('expected a {0!r}'.format(schema.cls), path)
iterable = _iterate_object(data)
iterable = ifilter(lambda item: item[1] is not None, iterable)
out = base_validate(path, iterable, {})
return type(data)(**out)
return validate_object
示例11: phase1
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def phase1(self): # Compute common names
a = dict(izip(imap(os.path.normcase, self.left_list), self.left_list))
b = dict(izip(imap(os.path.normcase, self.right_list), self.right_list))
self.common = map(a.__getitem__, ifilter(b.__contains__, a))
self.left_only = map(a.__getitem__, ifilterfalse(b.__contains__, a))
self.right_only = map(b.__getitem__, ifilterfalse(a.__contains__, b))
示例12: intersection
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def intersection(self, other):
"""Return the intersection of two sets as a new set.
(I.e. all elements that are in both sets.)
"""
if not isinstance(other, BaseSet):
other = Set(other)
if len(self) <= len(other):
little, big = self, other
else:
little, big = other, self
common = ifilter(big._data.__contains__, little)
return self.__class__(common)
示例13: difference_update
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def difference_update(self, other):
"""Remove all elements of another set from this set."""
data = self._data
if not isinstance(other, BaseSet):
other = Set(other)
if self is other:
self.clear()
for elt in ifilter(data.__contains__, other):
del data[elt]
# Python dict-like mass mutations: update, clear
示例14: test_itertools
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def test_itertools(self):
from itertools import imap, izip, ifilter
# We will assume that the itertools functions work, so provided
# that we've got identical coppies, we will work!
self.assertEqual(map, imap)
self.assertEqual(zip, izip)
self.assertEqual(filter, ifilter)
# Testing that filter(None, stuff) raises a warning lives in
# test_py3kwarn.py
示例15: first
# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import ifilter [as 別名]
def first(condition, seq):
try:
return next(ifilter(condition, seq))
except StopIteration:
return None