本文整理汇总了Python中operator.attrgetter方法的典型用法代码示例。如果您正苦于以下问题:Python operator.attrgetter方法的具体用法?Python operator.attrgetter怎么用?Python operator.attrgetter使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类operator
的用法示例。
在下文中一共展示了operator.attrgetter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: select_one
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def select_one(self, population: Population) -> Individual:
"""Return single individual from population.
Parameters
----------
population
A Population of Individuals.
Returns
-------
Individual
The selected Individual.
"""
tournament = choice(population, self.tournament_size, replace=False)
return min(tournament, key=attrgetter('total_error'))
示例2: save_attrgetter
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def save_attrgetter(self, obj):
"""attrgetter serializer"""
class Dummy(object):
def __init__(self, attrs, index=None):
self.attrs = attrs
self.index = index
def __getattribute__(self, item):
attrs = object.__getattribute__(self, "attrs")
index = object.__getattribute__(self, "index")
if index is None:
index = len(attrs)
attrs.append(item)
else:
attrs[index] = ".".join([attrs[index], item])
return type(self)(attrs, index)
attrs = []
obj(Dummy(attrs))
return self.save_reduce(operator.attrgetter, tuple(attrs))
示例3: update_archive_policy
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def update_archive_policy(self, name, ap_items):
with self.facade.independent_writer() as session:
ap = session.query(ArchivePolicy).get(name)
if not ap:
raise indexer.NoSuchArchivePolicy(name)
current = sorted(ap.definition,
key=operator.attrgetter('granularity'))
new = sorted(ap_items, key=operator.attrgetter('granularity'))
if len(current) != len(new):
raise indexer.UnsupportedArchivePolicyChange(
name, 'Cannot add or drop granularities')
for c, n in zip(current, new):
if c.granularity != n.granularity:
raise indexer.UnsupportedArchivePolicyChange(
name, '%s granularity interval was changed'
% utils.timespan_total_seconds(c.granularity))
# NOTE(gordc): ORM doesn't update JSON column unless new
ap.definition = ap_items
return ap
示例4: handle_plugins
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def handle_plugins(args):
result = []
errmsg = "**ERR** {0} ({1.__class__.__name__}: {1})"
for plugin in PLUGINS:
result.append('[{}]'.format(plugin))
eps = pkg_resources.iter_entry_points(plugin)
eps = sorted(eps, key=operator.attrgetter('name'))
for ep in eps:
try:
if hasattr(ep, 'resolve'):
ep.resolve()
else:
ep.load(require=False)
except Exception as e: # pylint: disable=broad-except
if args.verbose:
result.append(errmsg.format(ep, e))
else:
result.append(str(ep))
result.append('')
return result[:-1]
示例5: test_sorting
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def test_sorting(self):
pmts = [
IncomingPayment(transaction=Transaction(height=10)),
IncomingPayment(transaction=Transaction(height=12)),
IncomingPayment(transaction=Transaction(height=13)),
IncomingPayment(transaction=Transaction(height=None)),
IncomingPayment(transaction=Transaction(height=100)),
IncomingPayment(transaction=Transaction(height=None)),
IncomingPayment(transaction=Transaction(height=1))
]
for i in range(1680): # 1/3 of possible permutations
sorted_pmts = sorted(pmts, key=_ByHeight)
self.assertEqual(
list(map(attrgetter('height'), map(attrgetter('transaction'), sorted_pmts))),
[None, None, 100, 13, 12, 10, 1])
random.shuffle(pmts)
示例6: __init__
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def __init__(self, attr, needs=(), default=None, doc=None,
missing=None, copy=False):
needs = tuple(needs) if isinstance(needs, (tuple, list)) else (needs,)
if callable(attr):
self.fget = attr
self.attr = attr.__name__
if doc is None:
doc = attr.__doc__
else:
self.attr = attr
full_attr = '.'.join(needs+(attr,))
self.fget = operator.attrgetter(full_attr) if needs else None
if doc is None:
doc = "Link to " + full_attr.replace('_parent', 'parent')
self.needs = needs if '_parent' in needs else ('_parent',) + needs
self.default = default
self.missing = missing
self.copy = copy
self.__doc__ = doc
示例7: _manage_size
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def _manage_size(self):
while len(self) > self.capacity + self.capacity * self.threshold:
bytime = sorted(
dict.values(self),
key=operator.attrgetter("timestamp"),
reverse=True,
)
for item in bytime[self.capacity :]:
try:
del self[item.key]
except KeyError:
# if we couldn't find a key, most likely some other thread
# broke in on us. loop around and try again
break
# Regexp to match python magic encoding line
示例8: compile_members
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def compile_members(self,
members,
module_name,
sort_by_tag=False):
compiled_members = []
has_extension_marker = False
for member in members:
if member == EXTENSION_MARKER:
has_extension_marker = True
continue
if isinstance(member, list):
group_members, _ = self.compile_members(member,
module_name)
compiled_members.extend(group_members)
continue
compiled_member = self.compile_member(member, module_name)
compiled_members.append(compiled_member)
if sort_by_tag:
compiled_members = sorted(compiled_members, key=attrgetter('tag'))
return compiled_members, has_extension_marker
示例9: prepare_checkers
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def prepare_checkers(self):
"""return checkers needed for activated messages and reports"""
if not self.config.reports:
self.disable_reporters()
# get needed checkers
neededcheckers = [self]
for checker in self.get_checkers()[1:]:
messages = set(msg for msg in checker.msgs
if self.is_message_enabled(msg))
if (messages or
any(self.report_is_enabled(r[0]) for r in checker.reports)):
neededcheckers.append(checker)
# Sort checkers by priority
neededcheckers = sorted(neededcheckers,
key=operator.attrgetter('priority'),
reverse=True)
return neededcheckers
# pylint: disable=unused-argument
示例10: test_construction_with_alt_tz_localize
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def test_construction_with_alt_tz_localize(self, kwargs, tz_aware_fixture):
tz = tz_aware_fixture
i = pd.date_range('20130101', periods=5, freq='H', tz=tz)
kwargs = {key: attrgetter(val)(i) for key, val in kwargs.items()}
if str(tz) in ('UTC', 'tzutc()'):
warn = None
else:
warn = FutureWarning
with tm.assert_produces_warning(warn, check_stacklevel=False):
result = DatetimeIndex(i.tz_localize(None).asi8, **kwargs)
expected = DatetimeIndex(i, **kwargs)
tm.assert_index_equal(result, expected)
# localize into the provided tz
i2 = DatetimeIndex(i.tz_localize(None).asi8, tz='UTC')
expected = i.tz_localize(None).tz_localize('UTC')
tm.assert_index_equal(i2, expected)
# incompat tz/dtype
pytest.raises(ValueError, lambda: DatetimeIndex(
i.tz_localize(None).asi8, dtype=i.dtype, tz='US/Pacific'))
示例11: all
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def all(cls):
result = []
known_connections = KnownWifiConnection.all()
device = get_wifi_device()
aps = device.SpecificDevice().GetAllAccessPoints()
aps.sort(key=attrgetter('Frequency'), reverse=True)
aps.sort(key=attrgetter('Ssid'))
for ssid, grouper in groupby(aps, attrgetter('Ssid')):
if ssid:
# There often are more than one network for a given SSID (for
# example at 2.4 and 5GHz), so we keep only the one with the
# highest frequency.
ap = next(grouper)
result.append(cls(ap, device, known_connections))
return OrderedDict(
[(n.ssid, n) for n in sorted(
result, key=attrgetter('strength'), reverse=True)])
示例12: __init__
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def __init__(self, label=None, validators=None, query_factory=None,
get_pk=None, get_label=None, allow_blank=False,
blank_text='', **kwargs):
super(QuerySelectField, self).__init__(label, validators, **kwargs)
self.query_factory = query_factory
if get_pk is None:
if not has_identity_key:
raise Exception('The sqlalchemy identity_key function could not be imported.')
self.get_pk = get_pk_from_identity
else:
self.get_pk = get_pk
if get_label is None:
self.get_label = lambda x: x
elif isinstance(get_label, string_types):
self.get_label = operator.attrgetter(get_label)
else:
self.get_label = get_label
self.allow_blank = allow_blank
self.blank_text = blank_text
self.query = None
self._object_list = None
示例13: get_sample
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def get_sample(ggrp: GenomeGroup, ignore_coverage: bool) -> List[GenomeGroupTarget]:
"""Get the sample space for the mutation trials.
This will attempt to use covered-targets as the default unless ``ignore_coverage`` is set
to True. If the set .coverage file is not found then the total targets are returned instead.
Args:
ggrp: the Genome Group to generate the sample space of targets
ignore_coverage: flag to ignore coverage if present
Returns:
Sorted list of Path-LocIndex pairs as complete sample space from the ``GenomeGroup``.
"""
if ignore_coverage:
LOGGER.info("Ignoring coverage file for sample space creation.")
try:
sample = ggrp.targets if ignore_coverage else ggrp.covered_targets
except FileNotFoundError:
LOGGER.info("Coverage file does not exist, proceeding to sample from all targets.")
sample = ggrp.targets
# sorted list used for repeat trials using random seed instead of set
sort_by_keys = attrgetter(
"source_path",
"loc_idx.lineno",
"loc_idx.col_offset",
"loc_idx.end_lineno",
"loc_idx.end_col_offset",
)
return sorted(sample, key=sort_by_keys)
示例14: sorted_binop_expected_locs
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def sorted_binop_expected_locs(binop_expected_locs):
"""Sorted expected locs when used in tests for sample generation."""
sort_by = attrgetter("lineno", "col_offset", "end_lineno", "end_col_offset")
return sorted(binop_expected_locs, key=sort_by)
示例15: run_hooks
# 需要导入模块: import operator [as 别名]
# 或者: from operator import attrgetter [as 别名]
def run_hooks(cls, hooks):
"""Execute the indicated hooks, trapping errors.
Hooks with ``.failsafe == True`` are guaranteed to run
even if others at the same hookpoint fail. In this case,
log the failure and proceed on to the next hook. The only
way to stop all processing from one of these hooks is
to raise a BaseException like SystemExit or
KeyboardInterrupt and stop the whole server.
"""
assert isinstance(hooks, collections.abc.Iterator)
quiet_errors = (
cherrypy.HTTPError,
cherrypy.HTTPRedirect,
cherrypy.InternalRedirect,
)
safe = filter(operator.attrgetter('failsafe'), hooks)
for hook in hooks:
try:
hook()
except quiet_errors:
cls.run_hooks(safe)
raise
except Exception:
cherrypy.log(traceback=True, severity=40)
cls.run_hooks(safe)
raise