python中enumerate的用法实例解析

在python中enumerate的用法多用于在for循环中得到计数,本文即以实例形式向大家展现python中enumerate的用法。具体如下:

enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类。

示例代码如下所示:

<pre class="prism-highlight prism-language-python"><span style="font-size: 16px; font-family: 宋体, SimSun;">import string<br></br>s = string.ascii_lowercase<br></br>e = enumerate(s)<br></br>print (s,list(e))<br></br></span>

打印内容如下:

<pre class="prism-highlight prism-language-python">abcdefghijklmnopqrstuvwxyz [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p'), (16, 'q'), (17, 'r'), (18, 's'), (19, 't'), (20, 'u'), (21, 'v'), (22, 'w'), (23, 'x'), (24, 'y'), (25, 'z')]

在同时需要index和value值的时候可以使用 enumerate。

enumerate应用实例:

该实例中,line 是个 string 包含 0 和 1,要把1都找出来:

方法一:

<pre class="prism-highlight prism-language-python">def read_line(line):
  sample = {}
  n = len(line)
  for i in range(n):
    if line[i]!='0':
      sample[i] = int(line[i])
  return sample

方法二

<pre class="prism-highlight prism-language-python"><span style="font-size: 16px; font-family: 宋体, SimSun;">def xread_line(line):<br></br>    return ((idx, int(val)) for idx, val in enumerate(line) if val != '0')<br></br>print(read_line('0001110101'))<br></br>print(list(xread_line('0001110101')))</span>

打印内容如下:

<pre class="prism-highlight prism-language-python">{3: 1, 4: 1, 5: 1, 7: 1, 9: 1}
[(3, 1), (4, 1), (5, 1), (7, 1), (9, 1)]

posted @ 2020-08-26 16:41  沐风の萌龙  阅读(116)  评论(0)    收藏  举报