Python enumerate()

时间:2020-02-23 14:42:40  来源:igfitidea点击:

在本教程中,我们将学习Python enumerate()函数。
这是Python中的内置函数之一。

Python enumerate()

Python枚举取一个序列,然后将序列的每个元素变成一个元组。
元组的第一个元素是索引号。
元组的第二个元素是序列的值。

因此,简而言之,我们可以说枚举添加了一个带有序列元素的计数器。
python枚举函数的基本语法如下。

  • enumerate(sequence):此枚举函数创建一个枚举对象,其中索引从0开始。

  • enumerate(sequence,i):这使一个枚举对象的索引从i开始。

Python枚举列表

在本节中,我们将看到一个从列表或者任何其他序列创建枚举对象的示例。
在上一节中,我们学习了枚举函数,该函数将序列转换为枚举对象。
让我们看下面的例子。

# initialize a list of list
data = ['Love', 'Hate', 'Death', 123, ['Alice', 'Bob', 'Trudy']]

# print the type of variable 'data'
print('The type of data is :', type(data))  # output is 'list'

data = enumerate(data)
# again, print the type of variable 'data'
print('The type of data is now :', type(data))  # output is 'enumerate'

以下代码的输出将是

访问Python枚举对象

我们可以访问枚举对象。
我们可以使用for循环来访问枚举对象。
或者,我们可以将枚举对象转换为列表对象。

然后,我们可以像在python列表教程中那样遍历列表。
让我们看下面的例子来理解这一点。

# initialize a list of list
data = ['Love', 'Hate', 'Death', 123, ['Alice', 'Bob', 'Trudy']]
# make an enumerate object
enumObject = enumerate(data)

# access the enumerate object using loop
for element in enumObject:
  print(element)

print('\nStart index is changed to 100:')
# change the start index of the list to 100
enumObject = enumerate(data, 100)

# access the enumerate object using loop
for element in enumObject:
  print(element)

输出:

(0, 'Love')
(1, 'Hate')
(2, 'Death')
(3, 123)
(4, ['Alice', 'Bob', 'Trudy'])

Start index is changed to 100:
(100, 'Love')
(101, 'Hate')
(102, 'Death')
(103, 123)
(104, ['Alice', 'Bob', 'Trudy'])