Interpretation and visualization of enumerate function in Python

The role of enumerate()

In many cases, we need to get the index of an element when iterating over data pairing (that is, any object we can loop around).One way to achieve the desired results is to:

animals = ['dog', 'cat', 'mouse']
for i in range(len(animals)):
    print(i, animals[i])

Output:

0 dog
1 cat
2 mouse

Most developers with a C++ / Java background may choose this implementation, and iterating over the length of data objects through indexes is a familiar concept to them.However, this method is inefficient. We can use enumerate():

for i, j in enumerate(example):
    print(i, j)

enumerate() provides powerful functionality, such as when you need to get an index list:

(0, seq[0]), (1, seq[1]), (2, seq[2]), ...

Case Study 1: Enumerated Strings

Strings are just a list

To better understand string enumeration, we can think of a given string as a collection of individual characters (items).Therefore, the enumeration string will provide us with:

1. Index of characters. 2. The value of the character.

word = "Speed"
for index, char in enumerate(word):
    print(f"The index is '{index}' and the character value is '{char}'")

Output:

The index is '0' and the character value is 'S'
The index is '1' and the character value is 'p'
The index is '2' and the character value is 'e'
The index is '3' and the character value is 'e'
The index is '4' and the character value is 'd'

Case Study 2: List of Lists

So how should we make a list?To do this, we can use a for loop and iterate through each item's index and value:

sports = ['soccer', 'basketball', 't`  ennis']
for index, value in enumerate(sports):
    print(f"The item's index is {index} and its value is '{value}'")

Output:

The item's index is 0 and its value is 'soccer'
The item's index is 1 and its value is 'basketball'
The item's index is 2 and its value is 'tennis'

Case Study 3: Custom Start Index

We can see that enumerations start at index 0, but they often need to change their starting position to achieve more customization.Fortunately, enumerate() also has an optional parameter [start]

enumerate(iterable, start=0)

It can be used to indicate the starting position of an index by:

students = ['John', 'Jane', 'J-Bot 137']
for index, item in enumerate(students, start=1):
    print(f"The index is {index} and the list element is '{item}'")

output

The index is 1 and the list element is 'John'
The index is 2 and the list element is 'Jane'
The index is 3 and the list element is 'J-Bot 137'

Now, modify the above code: 1. The starting index can be negative; 2. If start = is omitted, it starts at the 0 index position by default.

teachers = ['Mary', 'Mark', 'Merlin']
for index, item in enumerate(teachers, -5):
    print(f"The index is {index} and the list element is '{item}'")

The output will be:

The index is -5 and the list element is 'Mary'
The index is -4 and the list element is 'Mark'
The index is -3 and the list element is 'Merlin'

Case study 4: Enumerating tuples

Using enumerated tuples follows the same logic as an enumerated list:

colors = ('red', 'green', 'blue')
for index, value in enumerate(colors):
    print(f"The item's index is {index} and its value is '{value}'")

Output:

The item's index is 0 and its value is 'red'
The item's index is 1 and its value is 'green'
The item's index is 2 and its value is 'blue'

Case Study 5: Enumerating tuples in a list

Let's go up one notch and combine multiple meta-groups into one list...We want to enumerate this tuple list.The code for one approach is as follows:

letters = [('a', 'A'), ('b', 'B'), ('c', 'C')]
for index, value in enumerate(letters):
    lowercase = value[0]
    uppercase = value[1]
    print(f"Index '{index}' refers to the letters '{lowercase}' and '{uppercase}'")

However, tuple unpacking has proven to be a more efficient method.For example:

letters = [('a', 'A'), ('b', 'B'), ('c', 'C')]
for i, (lowercase, uppercase) in enumerate(letters):
    print(f"Index '{i}' refers to the letters '{lowercase}' and '{uppercase}'")

Output:

Index '0' refers to the letters 'a' and 'A'
Index '1' refers to the letters 'b' and 'B'
Index '2' refers to the letters 'c' and 'C'

Case Study 6: Enumerating Dictionaries

Enumeration dictionaries appear to be similar to enumeration strings or lists, but this is not the case. The main difference is in their ordering structure, which is how the elements in a particular data structure are sorted.

Dictionaries are somewhat arbitrary because the order of their items is unpredictable.If we create a dictionary and print it, we will get a result:

translation = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
print(translation)
# Output on our computer: {'one': 'uno', 'two': 'dos', 'three': 'tres'}

However, if you print this dictionary, the order may be different!

Since indexes cannot access dictionary items, we must use a for loop to iterate over dictionary keys and values.The key-value is symmetrical to item, so we can use the.items() method:

animals = {'cat': 3, 'dog': 6, 'bird': 9}
for key, value in animals.items():
    print(key, value)

The output will be:

cat 3
dog 6
bird 9

First launched on WeChat Public Number: Machine Learning and Statistics ,

Keywords: Java

Added by Drizzt321 on Sun, 09 Feb 2020 05:15:18 +0200