原文中具体阐述了Python里的枚举类型函数公式enumerate()的实际使用方法,原文中根据实例编码推荐的十分详尽,对大家学习培训或工作具有很强的参照学习培训使用价值,必须的小伙伴们下边伴随着小编就来互相学习了解一下吧
相较于range,list等简单英语单词,enumerate光凭外观设计也不真的很让人愿用。实际上,enumerate或是非常好用的。
enumerate()是python的内置函数、适用python2.x和python3.x
enumerate在词典上有枚举类型、列出的含意
enumerate主要参数成可赋值/可迭代目标(如目录、字符串数组)
enumerate一般用于在for循环中获得记数,运用它能够同时拥有检索合值,即必须index和value值的时候也可以应用enumerate
enumerate()返回是个enumerate目标
python中最常见的算法设计便是list,解决list中每一个原素,一般会用for循环解决。
我们首先看,加入enumerate以后,list的改变:
多出一个检索,同时还可以载入到原素。这一特点有哪些作用呢?看这段编码:
ls=['a','b','c'] #method 1 for i in range(len(ls)): print(i,end='') print(ls<i>) #method 2 for s in ls: print(ls.index(s),end='') print(s) #method 3 for i,s in enumerate(ls): print(i,end='') print(s)
一看方法3就能更简便地访问到索引i和对应的元素s。
而且,用enumerate会显得代码更加高级~
enumerate的使用:
例如:已知lst=[1,2,3,4,5,6],要求输出:
0,1
1,2
2,3
3,4
4,5
5,6
>>>lst=[1,2,3,4,5,6] >>>for index,value in enumerate(lst): print('%s,%s'%(index,value)) 0,1 1,2 2,3 3,4 4,5 5,6
#指定索引从1开始 >>>lst=[1,2,3,4,5,6] >>>for index,value in enumerate(lst,1): print('%s,%s'%(index,value)) 1,1 2,2 3,3 4,4 5,5 6,6 #指定索引从3开始 >>>for index,value in enumerate(lst,3): print('%s,%s'%(index,value)) 3,1 4,2 5,3 6,4 7,5 8,6
补充:
如果要统计文件的行数,可以这样写:
count=len(open(filepath,'r').readlines())
这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。
可以利用enumerate():
count=0 for index,line in enumerate(open(filepath,'r')): count+=1
综上所述,这篇文章就给大家介绍到这里了,希望可以给大家带来帮助。
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/130281.html
...,'jack','ab'] 5.普遍几类迭代器:range、zip、enumerate、filter、reduce zip形成目录,形成词典 zip()函数公式接纳一连串可迭代对象做为主要参数,将不一样目标中相对应原素装包成数组(tuple),回到由这种数组...
...tf.square,tf.pow,tf.sqrt data.Dataset.from_tensor_slices GradientTape enumerate one_hot nn.softmax assign_sub argmax 下篇文章会讲利用神经网络实现鸢尾花分类的具体代码 Tensorflow的相关函数 强制tensor转换为该数据类型:tf.cast (张量名,dtype=数据类...
...iterable: print i, item i += 1 而是这样: for i, item in enumerate(iterable): print i, item Enumerate可以接受第二个参数,例如: >>> list(enumerate("abc")) [(0, "a"), (1, "b"), (2, "c")] >>> list(enumerate("abc", 1)) [(1, "a"), (2, "b"), (3, "c")] 字典/...
...1) print(list2) 枚举遍历 可以将下标及元素同时遍历 for i in enumerate(list1): print(i) for index,data in enumerate(list1): print(index, data) set1 = set([1,2,3]) # 让set也能有下标 for index,data in enumerate(set1): print(index, data)
阅读 153·2023-01-14 11:38
阅读 96·2023-01-14 11:04
阅读 50·2023-01-14 10:57
阅读 43·2023-01-14 10:48
阅读 57·2023-01-14 10:40
阅读 67·2023-01-14 10:34
阅读 51·2023-01-14 10:24
阅读 53·2023-01-14 10:18