Python note nine (iteration)

Source: Internet
Author: User

First, iteration

Through a for loop to iterate through a list, we call this traversal the same way as iteration . An iterative operation can be performed as long as an iterative object is available.

The following code can be used to determine whether an object is iterative.

A class is a collection of data types, such as,,, list tuple , and dict set str so on;

One is generator , including the generator and yield the generator function with the band (which we'll cover in the next section)

 from Import iterable>>> isinstance ("ABC", iterable) True>>> Isinstance ([],iterable] True>>> isinstance ({"name":"  Nadech"},iterable) True

Iterates through the contents of the list in an iterative way.

names = ["nadech","Aguilera","Sara"  ] for in names:    print(name)

If we want to add a sequence number to the index-element pair in front of the output name above, we can do so through the enumerate function.

names = ["nadech","Aguilera","Sara"  ] for in Enumerate (names):    print(i,name)

#输出结果

0 Nadech
1 Aguilera
2 Sara

In the dictionary iteration , we can iterate over the key,value of the dictionary , or the key-value pair .

>>> d = {"name":"Nadech"," Age":" A","Address":"Nanjing"}>>> forKeyinchd: #迭代key值...Print(Key) ... addressnameage>>> forValueinchd.values (): #迭代value值 ...Print(value) ... Nanjingnadech22>>> forKey,valueinchD.items (): #迭代key-value to ...Print(key,value) ... address nanjingname nadechage22

Similarly, there are two variables in a for loop, such as:

 for inch [(1, 1), (2, 4), (3, 9)]: ...      Print (x, y) ... 1 12 43 9

Python note nine (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.