當前位置: 首頁>>代碼示例>>Python>>正文


Python operator.attrgetter方法代碼示例

本文整理匯總了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')) 
開發者ID:erp12,項目名稱:pyshgp,代碼行數:18,代碼來源:selection.py

示例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)) 
開發者ID:pywren,項目名稱:pywren-ibm-cloud,代碼行數:20,代碼來源:cloudpickle.py

示例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 
開發者ID:gnocchixyz,項目名稱:gnocchi,代碼行數:21,代碼來源:sqlalchemy.py

示例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] 
開發者ID:latchset,項目名稱:custodia,代碼行數:22,代碼來源:__init__.py

示例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) 
開發者ID:monero-ecosystem,項目名稱:monero-python,代碼行數:18,代碼來源:test_transaction.py

示例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 
開發者ID:mhvk,項目名稱:baseband,代碼行數:22,代碼來源:file_info.py

示例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 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:19,代碼來源:util.py

示例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 
開發者ID:eerimoq,項目名稱:asn1tools,代碼行數:27,代碼來源:compiler.py

示例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 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:21,代碼來源:lint.py

示例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')) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:test_construction.py

示例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)]) 
開發者ID:ideascube,項目名稱:ideascube,代碼行數:23,代碼來源:wifi.py

示例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 
開發者ID:jpush,項目名稱:jbox,代碼行數:26,代碼來源:fields.py

示例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) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:34,代碼來源:run.py

示例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) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:6,代碼來源:conftest.py

示例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 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:29,代碼來源:_cprequest.py


注:本文中的operator.attrgetter方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。