What is an iteration

Source: Internet
Author: User

In Python, given a list or tuple, we can traverse the list or tuple through a for loop, which iterates over us as an iteration (iteration).

In Python, iterations are done through for ... in, and in many languages such as C or Java, the iteration list is done by subscript, such as Java code:

for (i=0; i<list.length; i++) {    n = list[i];}

As you can see, Python's for loop is more abstract than the Java for loop.

Because Python's for loop can be used not only on a list or a tuple, but also on any other object that can iterate.

Therefore, the iterative operation is for a collection, regardless of whether the collection is ordered or unordered, we can always use the For loop to remove each element of the collection in turn.

Note ordered Collection Unordered Collection unordered collections and have key-value pairs : dict

The iteration is a verb, which refers to an operation in Python, which is a for loop.

The biggest difference between iterating and accessing an array by subscript is that the latter is a concrete iterative implementation, which only cares about the iterative results and does not care how the iterations are implemented internally.

Task

Use the For loop to iterate through the algebraic column 1-100 and print a multiple of 7.

Reference code:

For I in Range (1,101):
If i%7==0:
Print I

Index iterations

In Python, iterations are always taken out of the element itself, not the index of the element.

For an ordered set, the element is indeed indexed. Sometimes we really want to get the index in the for loop, what do we do?

The method is to use the enumerate () function :

In enumerate (L): ...     Print index, '-', name ... 0-adam1-lisa2-bart3-paul

Using the enumerate () function, we can bind both index and element name in the For loop. However, this is not a special syntax for enumerate (). In fact, the enumerate () function puts:

[' Adam ', ' Lisa ', ' Bart ', ' Paul ']

Into something like this:

[(0, ' Adam '), (1, ' Lisa '), (2, ' Bart '), (3, ' Paul ')]

Therefore, each element of an iteration is actually a tuple:

In enumerate (L):    index = t[0]    name = t[1]    print index, '-', name

If we know that each tuple element contains two elements, the for loop can be further abbreviated as:

In enumerate (L):    print Index, '-', name

This not only makes the code simpler, but also reduces the number of two assignment statements.

It can be seen that the index iteration is not really indexed, but instead the enumerate () function automatically turns each element into a tuple (index, Element) and iterates over the index and the element itself.

Task

The zip () function can turn two lists into a list:

>>> zip ([ten, +,], [' A ', ' B ', ' C ']) [(Ten, ' A '), (+, ' B '), (+, ' C ')]

In the iteration [' Adam ', ' Lisa ', ' Bart ', ' Paul '], if we want to print out the rank-name (rank starting from 1), consider how to print it out in the iteration.

Tip: Consider using the zip () function and the range () function

Reference code:

L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
For index, name in Zip (range (1,len (l) +1), L):
Print index, '-', name

The value of the iteration Dict

We have learned that the Dict object itself is an iterative object , iterating the dict directly with a for loop, and can get a key for dict each time.

What should we do if we want to iterate over the value of the Dict object?

The Dict object has a values () method , which converts the dict into a list that contains all value, so that we iterate over each value of Dict:

D = {' Adam ': $, ' Lisa ': $, ' Bart ':}print d.values () # [+], 59]for V in d.values () : print V# 85# 95#          

If you read the Python document carefully, you can also see that dict, in addition to the values () method, has a itervalues ( ) method that replaces The Itervalues () method with the The values () method, the iteration effect is exactly the same:

D = {' Adam ': +, ' Lisa ': $, ' Bart ':}print d.itervalues () # <dictionary-valueiterator object at 0x106adbb50>   D.itervalues ():    print v# 85# 95#  

What is the difference between the two methods?

1. The values () method actually converts a dict to a list containing value.

2. However, the itervalues () method does not convert, and it takes value from dict in sequence during the iteration, so the Itervalues () method saves the memory needed to generate the list, compared to the values () method.

3. Print itervalues () find it returns a <dictionary-valueiterator> object, which shows that in Python, thefor loop can be used to iterate beyond list,tuple,str. Unicode,dict, and so on , any iterator object can be used for a for loop, and the inner iteration of how we usually don't care.

If an object says that it can iterate, then we iterate it directly with a for loop, which is an abstract data operation that does not require any data inside the iteration object.

Task

Given a dict:

D = {' Adam ': +, ' Lisa ': $, ' Bart ': ', ' Paul ': 74}

Please calculate the average score for all students.

Reference code:

D = {' Adam ': +, ' Lisa ': $, ' Bart ': ', ' Paul ': 74}

sum = 0.0
For V in D.values ():
Sum=sum+v
A=sum/len (d)

Print a

Iteration Dict Key and value

We learned how to iterate over the key and valueof dict, so can we iterate both key and value in a for loop? The answer is yes.

First, let's look at the values returned by the items () method of the Dict object:

>>> d = {' Adam ': $, ' Lisa ': $, ' Bart ':}>>> print d.items (' Lisa ', ' $ '), (' Adam ', $), (' Bart ', 5 9)]

As you can see, the items () method converts the Dict object to a list that contains a tuple, and we iterate over the list to get both key and value:

>>> for key, value in D.items ():     ... Print key, ': ', Value ... lisa:85adam:95bart:59

Like the values () has a itervalues (), items () also have a corresponding iteritems (), Iteritems () does not convert the dict to a list, but is constantly given in the iterative process Tuple, so Iteritems () does not occupy additional memory.

Task

Please follow dict:

D = {' Adam ': +, ' Lisa ': $, ' Bart ': ', ' Paul ': 74}

Print out the Name:score, and finally print out the average average:score.

Reference code:
D = {' Adam ': +, ' Lisa ': $, ' Bart ': ', ' Paul ': 74}

sum = 0.0
For K, V in D.items ():
sum = sum + V
Print K, ': ', V
Average=sum/len (d)
print ' average ', ': ', sum/le

What is an iteration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.