【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)
# <enumerate object at 0x0000028246E94C28>

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)) # <class 'list'>
print(ids)  
# ['11111111111', '2222222222222', '33333333333333333']
print(type(contents)) # <class 'list'>
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)) # <class 'list'>
print(finally_result)
# [{'id': '11111111111', 'label': 'positive'}, {'id': '2222222222222', 'label': 'positive'}, {'id': '33333333333333333', 'label': 'negative'}]

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别出BUG求求了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值