Beginner’s Guide to Python’ Enumerate Function
- 时间:2020-09-18 17:39:21
- 分类:网络文摘
- 阅读:148 次

python
You may see Python code like this:
1 2 | for i,v in enumerate(data): pass |
for i,v in enumerate(data): pass
So, what does the enumerate() function do? The enumerate() in python takes a list as its first parameter, and optionally support the second parameter, which is the start-index. By default, the index starts at zero.
The enumerate() returns an iterator.
1 2 3 4 5 | >>> a = ['a','b','c'] >>> enumerate(a) <enumerate object at 0x7f04d8738048> >>> list(enumerate(a)) [(0, 'a'), (1, 'b'), (2, 'c')] |
>>> a = ['a','b','c'] >>> enumerate(a) <enumerate object at 0x7f04d8738048> >>> list(enumerate(a)) [(0, 'a'), (1, 'b'), (2, 'c')]
The iterator can be converted to list, and we can see that the enumerate() will return an iterator of tuple, where the first element in the tuple is the incrementing index, and second element of the tuple is the corresponding value in the list. You can start the index from one, by passing the optional second parameter. See below:
1 2 | >>> list(enumerate(a, 1)) [(1, 'a'), (2, 'b'), (3, 'c')] |
>>> list(enumerate(a, 1)) [(1, 'a'), (2, 'b'), (3, 'c')]
You can combine the use of the zip() in Python that is also producing the same iterator, see below:
1 2 3 4 | >>> list(zip(range(len(a)), a)) [(0, 'a'), (1, 'b'), (2, 'c')] >>> list(enumerate(a)) [(0, 'a'), (1, 'b'), (2, 'c')] |
>>> list(zip(range(len(a)), a)) [(0, 'a'), (1, 'b'), (2, 'c')] >>> list(enumerate(a)) [(0, 'a'), (1, 'b'), (2, 'c')]
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:食品之辟谣系列:忽悠美容丰胸减肥的食物 冬季预防食物中毒及中毒后急救措施 四种常见的食物可以排出身体毒素 男人多吃一些香蕉对身体大有好处 冬至时节常吃6种传统食物可补阳防寒 南方黑芝麻糊大肠菌群超标 5批次产品不合格 烹饪技巧之烹调鸡蛋过程中的常见错误 全新认识冬季当家菜大白菜的营养价值 那些被人们误传的补充某种营养的食物 阿胶产品乱象:原料中被混入骡皮马皮
- 评论列表
-
- 添加评论