Detailed explanation of enumerate function in Python

enumerate is a built-in function of python, applicable to python2.x and python3.x. This function is used to combine a traversable data object (such as a list, tuple or string) into an index sequence and return an enumerate object instance.

Introduction

The usage of enumerate in Python is:

enumerate(sequence[,startindex=0])

The corresponding function is:

enumerate(iterable, start=0)

The parameter iterable is an iterable (traversable) data object instance, start indicates the starting value of the index, and an enumerate object is returned. Essentially enumerate is also an iterable object.

It can be understood that enumerate automatically adds an index value to each element of the iterable object, and then returns an enumerate object instance, and this instance is also an iterable object (you can use the for loop to traverse each element).

enumerate is mostly used to get the count in the for loop, and it can be used to get the index and value at the same time, that is, enumerate can be used when index and value are needed.

example

Example 1 : Add a number to "abcde" in the array:

s = ['a', 'b', 'c', 'd', 'e']
e = enumerate(s)
print(e)
for index, value in e:
    print('%s:%s' % (index, value))

Output result:

<enumerate object at 0x10e9ae340>
0:a
1:b
2:c
3:d
4:e

Example 2 : Start from the specified index.

s = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(s, 1):
    print('%s:%s' % (index, value))

Output result:

1:a
2:b
3:c
4:d
5:e

Case 3 : Count the number of lines of text.

The content of the text abc.txt is:

1213
12abc12
123r
abc12
cd
abc12
defgh

The example code is as follows:

with open("./abc.txt", 'r') as f:
    count = 0
    for index, line in enumerate(f):
        count += 1
    print(count)
f.close()

Output result:

7

Case 4 : Count the total number of lines of text and the number of occurrences of abc and the corresponding lines.

line_no = 0
words = 'abc'
result_line_list = []

with open("./abc.txt", 'r') as f:
    for index, line in enumerate(f):
        if "abc" in line:
            result_line_list.append(index)
        # 文本总行数
        line_no += 1
f.close()

print("文本总行数:%s" % line_no)
print(f"abc在文本中出现的次数为:{len(result_line_list)}次,具体行数为:{result_line_list}")

Output result:

文本总行数:7
abc在文本中出现的次数为:3次,具体行数为:[1, 3, 5]

Case 1 also demonstrates the function of parsing multiple variables using enumerate. Of course, you can also practice more levels of parameter variables.

Guess you like

Origin blog.csdn.net/wo541075754/article/details/130441250