In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the method of simplifying the cycle of the Python enumerate () counter". In the daily operation, I believe that many people have doubts about the method of simplifying the cycle of the Python enumerate () counter. The editor consulted all kinds of data and sorted out a simple and easy-to-use operation method. I hope it will be helpful to answer the doubt of "what is the method of simplifying the cycle of the Python enumerate () counter?" Next, please follow the editor to study!
1. For iterates in Python using loops
Loops in forPython use set-based iterations. This means that Python assigns the next item in the iteration to the loop variable at each iteration, as shown in the following example:
> values = ["a", "b", "c"] > for value in values:... Print (value)... abc
In this example, values is a list with three strings, "a", "b", and "c". In Python, a list is an iterable object. In the for loop, the loop variable is value. In each iteration of the loop, value is set to the next values of.
Next, we print the value to the screen. The advantage of set-based iteration is that it helps avoid the one-by-one errors common in other programming languages.
Now imagine that, in addition to the value itself, you want to print the index of the items in the list to the screen at each iteration.
One way to handle this task is to create a variable to store the index and update it at each iteration:
> index = 0 > for value in values:... Print (index, value)... Index + = 1.. 0a1 b2c
In this case, index is an integer that tracks your distance in the list. In each iteration of the loop, you print index and value. The last step of the loop is to update index one with the stored numbers.
When you forget that index is updated at each iteration, a common error occurs:
> index = 0 > for value in values:... Print (index, value)... 0 a0 b0 c
In this example, index keeps at at 0 every iteration, because there is no code to update its value at the end of the loop. This error is notoriously difficult to track, especially for long or complex loops.
Another common way to solve this problem is to use range () in conjunction with len () to automatically create an index. In this way, you do not need to remember to update the index:
> for index in range (len (values)):... Value = values [index]. Print (index, value)... 0 A1 b2 c
In this case, len (values) returns the length values, which is 3. Then range () creates an iterator that runs from the default starting value to 0 until it reaches len (values) minus one. In this case, index becomes your loop variable. In the loop, you set the current value to the item in value equals. Finally, you print and. Valuesindexindexvalue
In this example, a common error that can occur is that your value forgets to update at the beginning of each iteration. This is similar to the error of forgetting to update the index before. This is one of the reasons why the loop is not considered a Pythonic.
This example also has some limitations because values must allow access to its projects using integer indexes. Iterable objects that allow such access are called sequences in Python.
Technical details: according to the Python document, an iterable object is any object that can return one member at a time. By definition, iterable objects support the iterator protocol, which specifies how object members are returned when the object is used in the iterator.
There are two common types of iterability for Python:
Sequence
Generator
Any iterable object can be used in a for loop, but the sequence can only be accessed through an integer index.
An attempt to access an item through the index of a generator or iterator will raise a TypeError:
> enum = enumerate (values) > enum [0] Traceback (most recent call last): File ", line 1, in TypeError: 'enumerate' object is not subscriptable
In this example, you assign the return value enumerate () to enum. Enumerate () is an iterator, so trying to access its value through an index throws a TypeError.
Fortunately, Pythonenumerate () allows you to avoid all of these problems. It is a built-in function, which means that it has been available in every version of Python since it was added in Python 2.3 in 2003.
Second, using enumerate () of Python
You can use enumerate () in a loop in almost the same way as using the original iterable object. Instead of placing the iterable object directly after the for loop, put it in enumerate ().
We must also change the loop variable slightly, as shown in the following example:
> for count, value in enumerate (values):... Print (count, value)... 0 A1 b2 c
When we use enumerate (), the function returns two loop variables:
The count of the current iteration
The value of the project in the current iteration
Just like normal for loops, loop variables can be named at will. You use count and value in this example, but they can be named I and / v or any other valid Python name.
With enumerate (), you don't need to remember to access the project from an iterable object, and you don't need to remember to advance the index at the end of the loop. Everything is handled automatically by the magic of Python!
Technical details: using two loop variables count and value, separated by commas, is an example of parameter unpacking. This powerful Python feature will be discussed further later in this article.
Pythonenumerate () has an additional parameter that you can use to control the starting value of the count. By default, the starting value is 0 because the Python sequence type is indexed from zero. In other words, when you want to retrieve the first element of the list, you can use index 0:
> print (values [0]) a
We can see in this example that accessing 0 using the values index gives the first element a. In many cases, however, you may not want to count zeros starting with enumerate (). For example, you might want to print a natural count as the user's output. In this case, you can use the start parameter forenumerate () to change the starting count:
> for count, value in enumerate (values, start=1):... Print (count, value)... 1 a2 b3 c
In this case, you pass start=1, which starts with the value of the first loop iteration count. Compare this with the previous example, where the default value for start is 0 to see if you can find the difference.
Third, use Python to practice enumerate ()
We should enumerate () whenever we need to use counts and items in the loop. Keep in mind that enumerate () increments the count by one per iteration. However, this only slightly limits your flexibility. Because counting is a standard Python integer, you can use it in a number of ways. In the next few sections, you will see enumerate ().
1. Natural enumeration of iterated terms
In the previous section, you saw how to use enumerate () withstart to create a natural count number to print for the user. Enumerate () is also used like this in the Python code base. You can see an example in the script that reads the reST file and tells the user if there is a format problem.
Note: reST, also known as reStructured Text, is the standard format for text files used by Python for documents. You will often see strings in reST format as document strings in Python classes and functions. Scripts that read source code files and tell users about formatting problems are called linter because they look for metaphorical lint in the code.
This example is from rstlint. Don't worry too much about how this function checks for problems. The key is to demonstrate the use of enumerate () in the real world:
1def check_whitespace (lines): 2 "" Check for whitespace and line length issues. "" 3 for lno, line in enumerate (lines): 4 if "\ r" in line: 5 yield lno+1, "\\ r in line" 6 if "\ t" in line: 7 yield lno+1 "OMG TABSSecretaries 1" 8 if line [:-1] .rstrip ("\ t")! = line [:-1]: 9 yield lno+1, "trailing whitespace"
Check_whitespace () takes a parameter, lines, which is the file line that should be evaluated. In the third line check_whitespace (), enumerate () is used to loop over lines. This returns the line number, abbreviated as lno and line. Because start is not used, lno is a zero-based counter for lines in the file. Check_whitespace () then checks for inappropriate characters multiple times:
Enter (\ r)
Tabs (\ t)
Any space or tab at the end of the line
When one of these items exists, the current line number and useful message are generated for the user check_whitespace (). The count variable lno has been added to it so that it returns the count line number instead of the zero-based index. When the user rstlint.py reads the message, they will know which line to go to and what to fix.
two。 Skip conditional statements for a project
Using conditional statements to deal with projects is a very powerful technique. Sometimes you may only need to perform an operation on the first iteration of the loop, as shown in the following example:
> users = ["Test User", "Real User 1", "Real User 2"] > > for index, user in enumerate (users):. If index = = 0 Vol. Print ("Extra verbose output for:", user)... Print (user)... Extra verbose output for: Test UserReal User 1Real User 2
In this example, you use the list as the user's impersonation database. The first user is your test user, so you want to print additional diagnostic information about that user. Because you have set the system to test the user first, you can use the first index value of the loop to print additional detailed output.
We can also combine mathematical operations with the conditions of counting or indexing. For example, you might need to return items from iterable objects, but only if they have an even index. You can do this using the following methods of enumerate ():
> def even_items (iterable):... "" Return items from ``iterable`` when their index is even. " Values = []... For index, value in enumerate (iterable, start=1):... If not index% 2 Vol. Values.append (value)... Return values...
Even_items () takes a parameter named iterable, which should be some type of object that Python can loop through. First, the values is initialized to an empty list. Then you create a for loop with set. Iterableenumerate () start=1
Inside the for loop, you check whether the rest of the index passes 2 equals zero. If so, attach the project to values. Exe. Finally, you return to values.
You can use list deduction to do the same on a line without initializing an empty list, making the code more Pythonic:
> def even_items (iterable):... Return [v for i, v in enumerate (iterable, start=1) if not i% 2]...
In this sample code, even_items () uses a list derivation instead of a for loop to extract each item with an even index from the list.
You can even_items () to verify that it works as expected by getting an even index entry from a range of 1 to an integer. The result will be [2, 4, 6, 8, 10]:
> seq = list (range (1,11)) > > print (seq) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > even_items (seq) [2, 4, 6, 8, 10]
As expected, the even index item seq is returned from even_items (). This is not the most efficient way to get even numbers when you use integers. However, now that you have verified that even_items () works, you can get the even index letters of the ASCII alphabet:
> alphabet = "abcdefghijklmnopqrstuvwxyz" > even_items (alphabet) ['baked,' dashed, 'faded,' hagged, 'jacked,' lumped, 'nicked,' paired, 'rusted,' tweeted, 'vested,' Xerox,'z']
Alphabet is a string that contains all 26 lowercase letters of the ASCII alphabet. Calling even_items () and passing alphabet returns a list of alternating letters in the alphabet.
Python strings are sequences that can be used for looping and integer indexing and slicing. Therefore, for strings, you can use square brackets even_items () to achieve the same function more efficiently:
> list (alphabet [1:: 2]) ['baked,' dashed, 'faded,' hacked, 'jaded,' lumped, 'nicked,' paired, 'rusted,' tweeted, 'vested,' Xerox,'z']
Using string slicing here, you give the starting index 1, which corresponds to the second element. The indexing does not end after the first colon, so Python goes to the end of the string. Then add a second colon followed by a Python 2 so that all other elements will be adopted by the colon.
However, as you saw earlier, generators and iterators cannot be indexed or sliced, so you will still find them enumerate () useful. To continue the previous example, you can create a generator function that generates letters from the alphabet as needed:
> def alphabet ():... Alpha = "abcdefghijklmnopqrstuvwxyz"... For an in alpha:... Yield a > > alphabet [1:: 2] Traceback (most recent call last): File ", line 1, in TypeError: 'function' object is not subscriptable > even_items (alphabet ()) [' baked, 'dashed,' faded, 'hacked,' jaded, 'lumped,' nicked, 'paired,' rusted, 'tweeted,' vested, 'xpressed,' z']
In this example, you define a generator function that, when used in a loop, generates letters in the alphabet one by one. The Python function, whether it is a generator or a regular function, cannot be accessed through a square bracket index. If you try this on the second line, it will trigger a TypeError.
However, you can use the generator function in the loop, and you can pass alphabet () to even_items () on the last line. You can see that the result is the same as the previous two examples.
4. Understand Python enumerate ()
In the final sections, you saw examples of when and how enumerate () can take advantage. Now that you have mastered the actual aspect of enumerate (), you can learn more about how the function works internally.
To better understand how enumerate () works, you can use Python to implement your own version. Your version of enumerate () has two requirements. This should:
Accept an iterable and a starting count as parameters
Returns a tuple containing the current count value and related items of the iterable object
A way to write functions that meet these specifications is given in the Python documentation:
> def my_enumerate (sequence, start=0):... N = start... For elem in sequence:... Yield n, elem... N + = 1.
My_enumerate () accepts two parameters, sequence and start. The default value start is 0. In the function definition, you initialize the value start of n and for in sequence.
For each elem in sequence you yield control the location returned to the call and the current value n and elem sent back. Finally, you increment n to prepare for the next iteration. You can my_enumerate () to see the actual operation here:
> seasons = ["Spring", "Summer", "Fall", "Winter"] > > my_enumerate (seasons) > list (my_enumerate (seasons)) [(0, 'Spring'), (1,' Summer'), (2, 'Fall'), (3,' Winter')] > > list (my_enumerate (seasons, start=1)) [(1, 'Spring'), (2,' Summer'), (3, 'Fall'), (4,' Winter')]
First, you create a list of the four seasons to use. Next, you will show that a generator object is created by calling my_enumerate () with seasonsassequence. This is because you use the yield keyword to send the value back to the caller.
Finally, create two lists my_enumerate (), where the starting value is left as the default, where 0 is changed to 1, and a start is changed to 1. In both cases, you end up with a list of tuples, where the first element of each tuple is the count, and the second element is the value seasons from.
Although you enumerate () only need a few lines of Python code to implement the equivalent function, the actual code enumerate () is written in C. This means that it is super fast and efficient.
5. Unpacking parameter enumerate ()
When you use enumerate () in a for loop, you tell Python to use two variables, one for counting and the other for the value itself. You can do this by using a Python concept called parameter unpacking.
The idea of parameter unpacking is that a tuple can be divided into several variables according to the length of the sequence. For example, you can unpack a tuple that contains two elements into two variables:
> tuple_2 = (10, "a") > > first_elem, second_elem = tuple_2 > first_elem10 > > second_elem'a'
First, you create a tuple containing two elements, 10 and "a". Then unpack the tuple into the first_elemand second_elem, each assigning a value from the tuple.
When you call enumerate () and pass a series of values, Python returns an iterator. When you ask the iterator for its next value, it generates a tuple of two elements. The first element of the tuple is the count, and the second element is the value in the sequence you passed:
> values = ["a", "b"] > enum_instance = enumerate (values) > > enum_instance > next (enum_instance) (0,'a') > next (enum_instance) (1,'b') > next (enum_instance) Traceback (most recent call last): File ", line 1, in StopIteration
In this example, you create a list that values contains two elements "a" and "b". Then pass values to enumerate () and assign the return value to enum_instance. When you print enum_instance, you can see that it is an instance of enumerate () with a specific memory address.
Then use Python's built-in next () function from enum_instance. The first value returned by enum_instance is a tuple with a count of 0 and the first element from values, "a".
Next () calls on again to enum_instance to produce another tuple, this time counting 1 and the second element "b" from values. Finally, since there are no more values to return from, calling next () again will increase. StopIterationenum_instance
When an iterable object is used in a for loop, Python automatically calls next () at the beginning of each iteration until the StopIteration is thrown. Python assigns the value retrieved from the iterable object to the loop variable.
If an iterable object returns a tuple, you can use parameter unpacking to assign the elements of the tuple to multiple variables. This is what you did earlier in this tutorial by using two loop variables.
Another time you may have seen that the unpacking parameter using the for loop is using the built-in zip (), which allows you to iterate through two or more sequences at the same time.
In each iteration, zip () returns a tuple that collects elements from all passed sequences:
> first = ["a", "b", "c"] > second = ["d", "e", "f"] > third = ["g", "h", "I"] > for one, two, three in zip (first, second, third):. Print (one, two, three)... a d gb e hc f i
By using zip (), you can traverse first,second as well as third at the same time. In the for loop, you assign elements from firstto one, from secondtotwo, and from thirdto three. Then print three values.
We can combine zip () and enumerate () to unpack using nested parameters:
> for count, (one, two, three) in enumerate (zip (first, second, third)): Print (count, one, two, three)... 0 a d G1 b e H2 c f i
In the loop of for this example, you nest zip () in enumerate (). This means that each iteration of the for loop, enumerate () produces a tuple with the first value as a count and the second value as another tuple containing the element zip () from the parameter to. To extract the nested structure, you need to add parentheses from zip ().
There are other ways to simulate enumerate () and zip (). One method uses itertools.count (), which by default returns consecutive integers starting from zero. You can change the previous example to use itertools.count ():
For count, one, two, three in zip (itertools.count (), first, second, third):. Print (count, one, two, three)... 0 a d G1 b e H2 c f i
With itertools.count () in this example, you can use a single zip () call to generate a count and a loop variable with no nested parameters to unpack.
At this point, the study on "what is the method of simplifying the loop of Python enumerate () counter" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.