当前位置: 首页>>代码示例>>Python>>正文


Python builtins.enumerate方法代码示例

本文整理汇总了Python中builtins.enumerate方法的典型用法代码示例。如果您正苦于以下问题:Python builtins.enumerate方法的具体用法?Python builtins.enumerate怎么用?Python builtins.enumerate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在builtins的用法示例。


在下文中一共展示了builtins.enumerate方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: avg

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def avg(iterable):
    '''Return the average of all the elements of ``iterable``.'''

    # We walk over the iterable manually in case this is a generator
    total = 0
    num_vals = None
    for num_vals, val in builtins.enumerate(iterable, start=1):
        total += val

    if num_vals is None:
        raise SanityError('attempt to get average on an empty container')

    return total / num_vals


# Other utility functions 
开发者ID:eth-cscs,项目名称:reframe,代码行数:18,代码来源:sanity.py

示例2: count

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [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 
开发者ID:eth-cscs,项目名称:reframe,代码行数:18,代码来源:sanity.py

示例3: _get_callable_argspec_py2

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def _get_callable_argspec_py2(func):
    argspec = inspect.getargspec(func)
    varpos = argspec.varargs
    varkw = argspec.keywords
    args = argspec.args
    tuplearg = False
    for elem in args:
        tuplearg = tuplearg or isinstance(elem, list)
    if tuplearg:
        msg = 'tuple argument(s) found'
        raise FyppFatalError(msg)
    defaults = {}
    if argspec.defaults is not None:
        for ind, default in enumerate(argspec.defaults):
            iarg = len(args) - len(argspec.defaults) + ind
            defaults[args[iarg]] = default
    return args, defaults, varpos, varkw 
开发者ID:aradi,项目名称:fypp,代码行数:19,代码来源:fypp.py

示例4: __new__

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def __new__(cls, iterable, start=0):
        new_enumerate = _coconut.enumerate.__new__(cls, iterable, start)
        new_enumerate.iter = iterable
        new_enumerate.start = start
        return new_enumerate 
开发者ID:evhub,项目名称:pyprover,代码行数:7,代码来源:__coconut__.py

示例5: __repr__

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def __repr__(self):
        return "enumerate(%r, %r)" % (self.iter, self.start) 
开发者ID:evhub,项目名称:pyprover,代码行数:4,代码来源:__coconut__.py

示例6: __call__

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def __call__(self, *args, **kwargs):
        key = (args, _coconut.frozenset(kwargs))
        use_backup = False
        try:
            hash(key)
        except _coconut.Exception:
            try:
                key = _coconut.pickle.dumps(key, -1)
            except _coconut.Exception:
                use_backup = True
        if use_backup:
            for i, (k, v) in _coconut.enumerate(self.backup_tee_store):
                if k == key:
                    to_tee, store_pos = v, i
                    break
            else:  # no break
                to_tee = self.func(*args, **kwargs)
                store_pos = None
            to_store, to_return = _coconut_tee(to_tee)
            if store_pos is None:
                self.backup_tee_store.append([key, to_store])
            else:
                self.backup_tee_store[store_pos][1] = to_store
        else:
            self.tee_store[key], to_return = _coconut_tee(self.tee_store.get(key) or self.func(*args, **kwargs))
        return to_return 
开发者ID:evhub,项目名称:pyprover,代码行数:28,代码来源:__coconut__.py

示例7: enumerate

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def enumerate(iterable, start=0):
    '''Replacement for the built-in
    :func:`enumerate() <python:enumerate>` function.'''
    return builtins.enumerate(iterable, start) 
开发者ID:eth-cscs,项目名称:reframe,代码行数:6,代码来源:sanity.py

示例8: _get_call_arguments

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def _get_call_arguments(self, fname, spans, argexpr, contents, argnames):
        if argexpr is None:
            posargs = []
            kwargs = {}
        else:
            # Parse and evaluate arguments passed in call header
            self._evaluator.openscope()
            try:
                posargs, kwargs = self._evaluate(
                    '__getargvalues(' + argexpr + ')', fname, spans[0][0])
            except Exception as exc:
                msg = "unable to parse argument expression '{0}'"\
                    .format(argexpr)
                raise FyppFatalError(msg, fname, spans[0], exc)
            self._evaluator.closescope()

        # Render arguments passed in call body
        args = []
        for content in contents:
            self._evaluator.openscope()
            rendered = self.render(content, divert=True)
            self._evaluator.closescope()
            if rendered.endswith('\n'):
                rendered = rendered[:-1]
            args.append(rendered)

        # Separate arguments in call body into positional and keyword ones:
        if argnames:
            posargs += args[:len(args) - len(argnames)]
            offset = len(args) - len(argnames)
            for iargname, argname in enumerate(argnames):
                ind = offset + iargname
                if argname in kwargs:
                    msg = "keyword argument '{0}' already defined"\
                        .format(argname)
                    raise FyppFatalError(msg, fname, spans[ind + 1])
                kwargs[argname] = args[ind]
        else:
            posargs += args

        return posargs, kwargs 
开发者ID:aradi,项目名称:fypp,代码行数:43,代码来源:fypp.py

示例9: _postprocess_eval_lines

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def _postprocess_eval_lines(self, output, eval_inds, eval_pos):
        ilastproc = -1
        for ieval, ind in enumerate(eval_inds):
            span, fname = eval_pos[ieval]
            if ind <= ilastproc:
                continue
            iprev, eolprev = self._find_last_eol(output, ind)
            inext, eolnext = self._find_next_eol(output, ind)
            curline = self._glue_line(output, ind, iprev, eolprev, inext,
                                      eolnext)
            output[iprev + 1:inext] = [''] * (inext - iprev - 1)
            output[ind] = self._postprocess_eval_line(curline, fname, span)
            ilastproc = inext 
开发者ID:aradi,项目名称:fypp,代码行数:15,代码来源:fypp.py

示例10: _argsplit_fortran

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def _argsplit_fortran(argtxt):
    txt = _INLINE_EVAL_REGION_REGEXP.sub(_blank_match, argtxt)
    splitpos = [-1]
    quote = None
    closing_brace_stack = []
    closing_brace = None
    for ind, char in enumerate(txt):
        if quote:
            if char == quote:
                quote = None
            continue
        if char in _QUOTES_FORTRAN:
            quote = char
            continue
        if char in _OPENING_BRACKETS_FORTRAN:
            closing_brace_stack.append(closing_brace)
            ind = _OPENING_BRACKETS_FORTRAN.index(char)
            closing_brace = _CLOSING_BRACKETS_FORTRAN[ind]
            continue
        if char in _CLOSING_BRACKETS_FORTRAN:
            if char == closing_brace:
                closing_brace = closing_brace_stack.pop(-1)
                continue
            else:
                msg = "unexpected closing delimiter '{0}' in expression '{1}' "\
                      "at position {2}".format(char, argtxt, ind + 1)
                raise FyppFatalError(msg)
        if not closing_brace and char == _ARGUMENT_SPLIT_CHAR_FORTRAN:
            splitpos.append(ind)
    if quote or closing_brace:
        msg = "open quotes or brackets in expression '{0}'".format(argtxt)
        raise FyppFatalError(msg)
    splitpos.append(len(txt))
    fragments = [argtxt[start + 1 : end]
                 for start, end in zip(splitpos, splitpos[1:])]
    return fragments 
开发者ID:aradi,项目名称:fypp,代码行数:38,代码来源:fypp.py

示例11: plot_power_spectrum_two_layers

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def plot_power_spectrum_two_layers(powers_negative, powers_positive, times, title='', figure_fname='',
                                   only_power_spectrum=True, high_gamma_max=120):
    if not only_power_spectrum:
        fig, (ax1, ax2, ax3) = plt.subplots(3)#, sharex=True)
    else:
        fig, ax1 = plt.subplots()
    F, T = powers_negative.shape
    freqs = np.concatenate([np.arange(1, 30), np.arange(31, 60, 3), np.arange(60, high_gamma_max + 5, 5)])
    bands = dict(delta=[1, 4], theta=[4, 8], alpha=[8, 15], beta=[15, 30], gamma=[30, 55],
                 high_gamma=[65, high_gamma_max])

    im1 = _plot_powers(powers_negative, ax1, times, freqs)
    # cba = plt.colorbar(im1, shrink=0.25)
    im2 = _plot_powers(powers_positive, ax1, times, freqs)
    cbb = plt.colorbar(im2, shrink=0.25)
    plt.ylabel('frequency (Hz)')
    plt.xlabel('Time (s)')
    plt.title(title)

    if not only_power_spectrum:
        for band_name, band_freqs in bands.items():
            idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
            band_power = np.mean(powers_negative[idx, :], axis=0)
            ax2.plot(band_power.T, label=band_name)
        ax2.set_xlim([0, T])
        # ax2.legend()

        for band_name, band_freqs in bands.items():
            idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
            band_power = np.mean(powers_positive[idx, :], axis=0)
            ax3.plot(band_power.T, label=band_name)
        ax3.set_xlim([0, T])
        # ax3.legend()

    if figure_fname != '':
        print('Saving figure to {}'.format(figure_fname))
        plt.savefig(figure_fname, dpi=300)
        plt.close()
    else:
        plt.show() 
开发者ID:pelednoam,项目名称:mmvt,代码行数:42,代码来源:power_spectrums_plots.py

示例12: calc_band_power

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def calc_band_power(powers, freqs, band_freqs):
    idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
    return np.mean(powers[idx, :], axis=0) 
开发者ID:pelednoam,项目名称:mmvt,代码行数:5,代码来源:power_spectrums_plots.py

示例13: plot_positive_and_negative_power_spectrum

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def plot_positive_and_negative_power_spectrum(
        powers_negative, powers_positive, times, title='', figure_fname='',
        only_power_spectrum=True, show_only_sig_in_graph=True, sig_threshold=2, high_gamma_max=120,
        min_f=1):
    from src.utils import color_maps_utils as cmu
    YlOrRd = cmu.create_YlOrRd_cm()
    PuBu = cmu.create_PuBu_cm()

    freqs = epi_utils.get_freqs(min_f, high_gamma_max)
    bands = epi_utils.calc_bands(min_f, high_gamma_max)

    if show_only_sig_in_graph:
        powers_positive[np.where(np.abs(powers_positive) < sig_threshold)] = 0
        powers_negative[np.where(np.abs(powers_negative) < sig_threshold)] = 0

    min_t, max_t = round(times[0], 1), round(times[-1], 1)
    fig, axs = plt.subplots(2, 2)
    pos_powers_ax, neg_powers_ax = axs[0, 0], axs[0, 1]
    pos_graph_ax, neg_graph_ax = axs[1, 0], axs[1, 1]
    pos_powers_ax.title.set_text('Positives')
    neg_powers_ax.title.set_text('Negatives')
    neg_cmap_vmin_vmax = (PuBu, np.min(powers_negative), -2 if show_only_sig_in_graph else 0)
    pos_cmap_vmin_vmax = (YlOrRd, 2 if show_only_sig_in_graph else 0, np.max(powers_positive))
    im1 = _plot_powers(powers_negative, neg_powers_ax, times, freqs, neg_cmap_vmin_vmax)
    # cba = plt.colorbar(im1, ax=neg_powers_ax,  shrink=0.25)
    im2 = _plot_powers(powers_positive, pos_powers_ax, times, freqs, pos_cmap_vmin_vmax)
    # cbb = plt.colorbar(im2, ax=pos_graph_ax, shrink=0.25)

    for band_name, band_freqs in bands.items():
        idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
        band_power = np.mean(powers_negative[idx, :], axis=0)
        neg_graph_ax.plot(times, band_power.T, label=band_name)
    neg_graph_ax.set_xlim([min_t, max_t])
    neg_graph_ax.set_ylim([None, -2 if show_only_sig_in_graph else 0])
    neg_graph_ax.legend()

    for band_name, band_freqs in bands.items():
        band_power = calc_band_power(powers_positive, freqs, band_freqs)
        pos_graph_ax.plot(times, band_power.T, label=band_name)
    pos_graph_ax.set_xlim([min_t, max_t])
    pos_graph_ax.set_ylim([2 if show_only_sig_in_graph else 0, None])

    # pos_graph_ax.legend()
    plt.suptitle(title)

    if figure_fname != '':
        print('Saving figure to {}'.format(figure_fname))
        plt.savefig(figure_fname, dpi=300)
        plt.close()
    else:
        plt.show() 
开发者ID:pelednoam,项目名称:mmvt,代码行数:53,代码来源:power_spectrums_plots.py

示例14: calc_induced_power

# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import enumerate [as 别名]
def calc_induced_power(subject, run_num, windows_fnames, modality, inverse_method='dSPM', check_for_labels_files=True,
                       overwrite=False):

    def files_exist(window_fname):
        fol = op.join(root_dir, '{}-epilepsy-{}-{}-{}-induced_power'.format(
            subject, inverse_method, modality, utils.namebase(window_fname)))
        if not op.isdir(fol):
            return False
        files = glob.glob(op.join(fol, 'epilepsy_*_induced_power.npy'))
        if len(files) < 62:
            return False
        for fname in files:
            # file_mod_time = utils.file_modification_time_struct(fname)
            # if not (file_mod_time.tm_year >= 2019 and (file_mod_time.tm_mon == 7 and file_mod_time.tm_mday >= 10) or \
            #         (file_mod_time.tm_mon > 7)):
            if not utils.file_mod_after_date(fname, 10, 7, 2019):
                return False
        return True

    root_dir = op.join(EEG_DIR if modality == 'eeg' else MEG_DIR, subject)
    module = eeg if modality == 'eeg' else meg
    files_to_calc = [utils.namebase(window_fname) for window_fname in windows_fnames if not files_exist(window_fname)]
    if len(files_to_calc) == 0 and not overwrite:
        print('All files exist!')
        return
    else:
        print('Files needed to recalc:')
        for ind, fname in enumerate(files_to_calc):
            print('{}: {}'.format(ind + 1, fname))
        # ret = input('Do you want to continue (y/n)? ')
        # if not au.is_true(ret):
        #     return
    # output_fname = op.join(MMVT_DIR, 'eeg' if modality == 'eeg' else 'meg', '{}-epilepsy-{}-{}-{}_{}'.format(
    #     subject, inverse_method, modality, '{window}', '{band}'))
    for window_fname in windows_fnames:
        print('{} {} {}:'.format(subject, modality, utils.namebase(window_fname)))
        if files_exist(window_fname) and not overwrite:
            print('Already exist')
            continue
        args = module.read_cmd_args(dict(
            subject=subject,
            mri_subject=subject,
            function='calc_stc',
            task='epilepsy',
            inverse_method=inverse_method,
            inv_fname=op.join(root_dir, '{}-epilepsy{}-{}-inv.fif'.format(subject, run_num, modality)),
            fwd_fname=op.join(root_dir, '{}-epilepsy{}-{}-fwd.fif'.format(subject, run_num, modality)),
            calc_source_band_induced_power=True,
            fwd_usingEEG=modality in ['eeg', 'meeg'],
            evo_fname=window_fname,
            n_jobs=1,
            overwrite_stc=overwrite
        ))
        module.call_main(args) 
开发者ID:pelednoam,项目名称:mmvt,代码行数:56,代码来源:pipeline.py


注:本文中的builtins.enumerate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。