python中enumerate的用法实例解析
在python中enumerate的用法多用于在for循环中得到计数,本文即以实例形式向大家展现python中enumerate的用法。具体如下:
enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类。
示例代码如下所示:
import string s = string.ascii_lowercase e = enumerate(s) print s print list(e)
输出为:
abcdefghij [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]
在同时需要index和value值的时候可以使用 enumerate。
enumerate应用实例:
该实例中,line 是个 string 包含 0 和 1,要把1都找出来:
方法一:
def read_line(line): sample = {} n = len(line) for i in range(n): if line[i]!='0': sample[i] = int(line[i]) return sample
方法二:
def xread_line(line): return((idx,int(val)) for idx, val in enumerate(line) if val != '0') print read_line('0001110101') print list(xread_line('0001110101'))
相信本文示例对大家加深对Python中enumerate的用法能够起到一定的帮助作用。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the advantages and disadvantages of templating?

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers

Share several .NET open source AI and LLM related project frameworks
