码迷,mamicode.com
首页 > 编程语言 > 详细

enumerate() -- Python

时间:2017-08-29 21:45:51      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:exp   color   coding   local   元组   find   字符串   print   返回   

#!usr/bin/env python
#coding:utf-8
‘‘‘
enumerate()说明:
    1、enumerate()是Python的内置函数;
    2、enumerate字面上是枚举、列举的意思;
    3、对于一个可迭代、可遍历的对象(列表、元组、字符串),enumerate将其组成一个索引序列,利用
        它可以同时获得索引和值;
    4、enumerate多用于for循环中得到计数;
    5、注意:enumerate()返回的是enumerate对象;

‘‘‘

‘‘‘
需求:给定一串数字01098040234,将非0的数字所处的位置及值进行打印输出;
‘‘‘
str1 = 01098040234
def findNotZero(str):
    return ((index,value) for index,value in enumerate(str) if value!=0)

print(findNotZero(str1))

 

 5、注意:enumerate()返回的是enumerate对象--运行结果如下所示

 

<generator object findNotZero.<locals>.<genexpr> at 0x00000223A8416A98>
[Finished in 0.1s]

 

 

#!usr/bin/env python
#coding:utf-8
‘‘‘
enumerate()说明:
    1、enumerate()是Python的内置函数;
    2、enumerate字面上是枚举、列举的意思;
    3、对于一个可迭代、可遍历的对象(列表、元组、字符串),enumerate将其组成一个索引序列,利用
        它可以同时获得索引和值;
    4、enumerate多用于for循环中得到计数;
    5、注意:enumerate()返回的是enumerate对象;

‘‘‘

‘‘‘
需求:给定一串数字01098040234,将非0的数字所处的位置及值进行打印输出;
‘‘‘
str1 = 01098040234
def findNotZero(str):
    return ((index,value) for index,value in enumerate(str) if value!=0)

print(list(findNotZero(str1)))

 

运行结果:

[(1, 1), (3, 9), (4, 8), (6, 4), (8, 2), (9, 3), (10, 4)]
[Finished in 0.1s]

 

 

注意点:

1、enumerate()指定起始下标enumerate(str,1)

2、列表解析式:[expr for iter_var in iterable if cond_expr]

 

enumerate()的优势:

需求:给你一个列表[‘我’,‘是’,‘寒’,‘岳’];现在想要同时将每个列表元素的索引位置及值同时打印输出;

最直接的做法就是:

for i in range(len(list1)):
    print (i,list1[i])

运行结果:

0 我
123 岳
[Finished in 0.2s]

 

上述方法有些累赘,利用enumerate()会更加直接和优美:

list1 = [,,,]
for index,value in enumerate(list1):
    print(index,value)

运行结果:

0 我
123 岳
[Finished in 0.1s]

 

enumerate() -- Python

标签:exp   color   coding   local   元组   find   字符串   print   返回   

原文地址:http://www.cnblogs.com/licl11092/p/7450157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!