enumerate()是python的內(nèi)置函數(shù),適用于python2.x和python3.x;
enumerate在字典賞識枚舉、列舉的意思;
enumerate參數(shù)為可遍歷/可迭代的對象(如列表、字符串);
enumerate多用于在for循環(huán)中得到計數(shù),利用它可以同時獲得索引和值,即需要 index 和 value 值的時候可以使用enumerate;
enumerate()返回的是一個enumerate對象 。
s = [1, 2, 3, 4, 5]
e = enumerate(s)
print(e)
# <enumerate object at 0x0000028246E94C28>
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
例:將一組字典列表中的某一對字典元素與另一組字典列表中某一對字典元素組成一組新的字典列表文章來源:http://www.zghlxwxcb.cn/news/detail-587237.html
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'}]
詳情解析:文章來源地址http://www.zghlxwxcb.cn/news/detail-587237.html
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'}]
到了這里,關于Python中enumerate用法詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!