如何在 Python 中使用 enumerate 函数实现带索引的循环

2023-03-31 00:00:00 索引 函数 循环

在 Python 中,我们可以使用 enumerate 函数来遍历一个序列(列表、元组、字符串等)并在每次循环中同时获得元素和它的索引。这样可以在循环中轻松地使用索引对序列中的元素进行操作。

下面是使用 enumerate 函数实现带索引的循环的示例代码:

str1 = "pidancode.com"
str2 = "皮蛋编程"

for i, char in enumerate(str1):
    print(f"char at position {i}: {char}")

输出:

char at position 0: p
char at position 1: i
char at position 2: d
char at position 3: a
char at position 4: n
char at position 5: c
char at position 6: o
char at position 7: d
char at position 8: e
char at position 9: .
char at position 10: c
char at position 11: o
char at position 12: m

在这个例子中,我们使用 enumerate 函数遍历了字符串 str1 中的每个字符,并通过变量 i 获得了当前字符在字符串中的索引。这样我们可以方便地在循环中对每个字符进行操作。

如果我们要同时遍历两个序列并且需要它们对应的索引,可以将它们打包成一个 zip 对象,然后对 zip 对象使用 enumerate 函数:

str1 = "pidancode.com"
str2 = "皮蛋编程"

for i, (char1, char2) in enumerate(zip(str1, str2)):
    print(f"char at position {i} in str1: {char1}")
    print(f"char at position {i} in str2: {char2}\n")

输出:

char at position 0 in str1: p
char at position 0 in str2: 皮

char at position 1 in str1: i
char at position 1 in str2: 蛋

char at position 2 in str1: d
char at position 2 in str2: 编

char at position 3 in str1: a
char at position 3 in str2: 程

char at position 4 in str1: n
char at position 4 in str2: 序

char at position 5 in str1: c
char at position 5 in str2: 在

char at position 6 in str1: o
char at position 6 in str2: 线

char at position 7 in str1: d
char at position 7 in str2: 上

char at position 8 in str1: e
char at position 8 in str2: ,

char at position 9 in str1: .
char at position 9 in str2: 

char at position 10 in str1: c
char at position 10 in str2: 

char at position 11 in str1: o
char at position 11 in str2: 

char at position 12 in str1: m
char at position 12 in str2: 

在这个例子中,我们使用 zip函数将两个字符串 str1 和 str2 打包成了一个 zip 对象,然后使用 enumerate 函数遍历这个对象。在每次循环中,我们同时获得了当前字符在字符串中的索引 i 和它们在字符串中对应的字符 char1 和 char2。这样,我们可以轻松地在循环中对每个字符进行操作,并获得它们在两个字符串中对应的值。

需要注意的是,如果两个序列的长度不同,zip 函数将在较短的序列用尽后停止迭代。在上面的例子中,由于字符串 str1 的长度比 str2 长,因此最后几个字符在 str2 中没有对应值。如果需要,可以使用 Python 的内置函数 itertools.zip_longest() 来在较短的序列用尽后填充默认值。

除了在循环中使用 enumerate 函数外,它还可以用于创建字典或列表。例如,以下代码演示了如何使用 enumerate 函数创建一个字典,其中键是字符串 str1 中的字符,值是该字符在字符串中的索引:

str1 = "pidancode.com"
index_dict = {}

for i, char in enumerate(str1):
    index_dict[char] = i

print(index_dict)

输出:

{'p': 0, 'i': 1, 'd': 2, 'a': 3, 'n': 4, 'c': 5, 'o': 6, 'e': 8, '.': 9, 'm': 12}

在这个例子中,我们遍历了字符串 str1 中的每个字符,并使用 enumerate 函数获得了每个字符在字符串中的索引 i。然后,我们将字符作为键,索引作为值,将它们添加到一个字典 index_dict 中。这样,我们就可以通过字符来查找它在字符串中的位置。

总之,enumerate 函数是一个很有用的工具,它允许我们在循环中获得序列元素的索引,并在一些情况下可以简化代码并提高可读性。

相关文章