【python】enumerate函数用法

1. enumerate()介绍

enumerate()是python的内置函数,适用于python2.x和python3.x;
enumerate在字典赏识枚举、列举的意思;
enumerate参数为可遍历/可迭代的对象(如列表、字符串);
enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要 index 和 value 值的时候可以使用enumerate;

enumerate()返回的是一个enumerate对象 。如:

s = [1, 2, 3, 4, 5]
e = enumerate(s)
print(e)
# 

2. enumerate的使用:

例如:已知s = [1,2,3,4,5,6],要求输出: 0,1 1,2 2,3 3,4 4,5 5,6

例1:

s = [1, 2, 3, 4, 5]
x = enumerate(s)
for index,value in x:
    print("%s,%s"%(index,value))
    
# 0,1
# 1,2
# 2,3
# 3,4
# 4,5

例2:



s = [1, 2, 3, 4, 5]
# 索引从1开始
for index,value in enumerate(s, 1):
    print("%s,%s" %(index,value))

# 1,1
# 2,2
# 3,3
# 4,4
# 5,5

3. 例子

将一组字典列表中的某一对字典元素与另一组字典列表中某一对字典元素组成一组新的字典列表

notes = [{'id': '11111111111', 'content': 'lalallalalalallala'}, {'id': '2222222222222', 'content': 'qqqqqqqqqqqqqqqqqqq'}, {'id': '33333333333333333', 'content': 'aaaaaaaaaaaaaaaaa'}]
ids = [one_note["id"] for one_note in notes]
contents = [one_note["content"] for one_note in notes]
result = [{'id': '11111111111', 'label': 'positive'}, {'id': '2222222222222', 'label': 'positive'}, {'id': '33333333333333333', 'label': 'negative'}]
finally_result = [{"id": ids[index], "label": label["label"]} for index,label in enumerate(result)]
print(finally_result)
# [{'id': '11111111111', 'label': 'positive'}, {'id': '2222222222222', 'label': 'positive'}, {'id': '33333333333333333', 'label': 'negative'}]

详情解析:

notes = [{'id': '11111111111', 'content': 'lalallalalalallala'}, {'id': '2222222222222', 'content': 'qqqqqqqqqqqqqqqqqqq'}, {'id': '33333333333333333', 'content': 'aaaaaaaaaaaaaaaaa'}]
ids = [one_note["id"] for one_note in notes]
contents = [one_note["content"] for one_note in notes]
print(type(ids)) # 
print(ids)  
# ['11111111111', '2222222222222', '33333333333333333']
print(type(contents)) # 
print(contents) 
# ['lalallalalalallala', 'qqqqqqqqqqqqqqqqqqq', 'aaaaaaaaaaaaaaaaa']
result = [{'id': '11111111111', 'label': 'positive'}, {'id': '2222222222222', 'label': 'positive'}, {'id': '33333333333333333', 'label': 'negative'}]
finally_result = [{"id": ids[index], "label": label["label"]} for index,label in enumerate(result)]
print(type(finally_result)) # 
print(finally_result)
# [{'id': '11111111111', 'label': 'positive'}, {'id': '2222222222222', 'label': 'positive'}, {'id': '33333333333333333', 'label': 'negative'}]

你可能感兴趣的:(python,python,numpy,开发语言,enumerate)