日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python enumerate函數用法

作者:別出BUG求求了 更新時間: 2023-11-12 編程語言

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'}]

原文鏈接:https://blog.csdn.net/weixin_39589455/article/details/130505471

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新