本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
enumerate(iterable, start=0)
-
iterable:一个可迭代对象,比如列表、元组或字符串; -
start:一个可选参数,用于指定计数的起始值,默认为0。
返回值:
def enumerate(iterable, start=0):
n = start
for elem in iterable:
yield n, elem
n += 1
下面是一些使用 enumerate() 函数的示例:
-
示例 1:基本使用
fruits = ['apple', 'banana', 'cherry']
enumerate(fruits)
# 输出:<enumerate at 0x20d25873c90>
list(enumerate(fruits))
# 输出:[(0, 'apple'), (1, 'banana'), (2, 'cherry')]
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
# 输出:Index: 0, Fruit: apple
# Index: 1, Fruit: banana
# Index: 2, Fruit: cherry
-
示例 2:指定起始索引(start参数)
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
print(f"Index: {index}, Fruit: {fruit}")
# 输出:Index: 1, Fruit: apple
# Index: 2, Fruit: banana
# Index: 3, Fruit: cherry
-
示例 3:在字符串上使用
for index, char in enumerate("hello"):
print(f"Index: {index}, Character: {char}")
# 输出:Index: 0, Character: h
# Index: 1, Character: e
# Index: 2, Character: l
# Index: 3, Character: l
# Index: 4, Character: o


本篇文章来源于微信公众号: 码农设计师