In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "detailed introduction of loop functions in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
I. cyclic function
1. For cycle
2. While cycle
3. Interrupt the cycle
Second, cycle design
1. Range ()
2. Enumerate ()
3. Zip ()
III. Circular objects
1. What is a circular object
2. Iterator
3. Generator
4. Table derivation
1. Cyclic function 1. For loop
The for loop needs to set the number of times (n) of the loop in advance, and then execute the statements belonging to the for n times.
The basic structure is
For element in sequence: statement
For example, we edit a file called forDemo.py
For an in [3. 4. 4. 4]: print a
This loop takes one element at a time from the table [3 for 4.4] (recall: the table is a sequence), assigns that element to a, and then performs the operations belonging to the table (print).
Introduce a new Python function range () to help you set up the table.
Idx = range (5) print idx
You can see that the idx is [0pr 1pm 2pm 3pr 4]
The function of this function is to create a new table. The elements of this table are all integers, starting from 0, the next element is 1 larger than the previous one, until the upper limit written in the function (excluding the upper limit itself)
(for range (), there is a wealth of usage. If you are interested, you can refer to it. In Python 3, the usage of range () has changed, see the comments section.)
For example:
For an in range (10): print aura 22, while cycle
The usage of while is
While condition: statement
While iterates through statements that belong to it until the condition is False.
For example:
While i
< 10: print i i = i + 13、中断循环 continue :在循环的某一次执行中,如果遇到continue, 那么跳过这一次执行,进行下一次的操作 break :停止执行整个循环 for i in range(10): if i == 2: continue print i 当循环执行到i = 2的时候,if条件成立,触发continue, 跳过本次执行(不执行print),继续进行下一次执行(i = 3)。 for i in range(10): if i == 2: break print i 当循环执行到i = 2的时候,if条件成立,触发break, 整个循环停止。 二、循环设计1、range() 在Python中,for循环后的in跟随一个序列的话,循环每次使用的序列元素,而不是序列的下标。 之前我们已经使用过range()来控制for循环。现在,我们继续开发range的功能,以实现下标对循环的控制: S = 'abcdefghijk'for i in range(0,len(S),2): print S[i] 在该例子中,我们利用len()函数和range()函数,用i作为S序列的下标来控制循环。在range函数中,分别定义上限,下限和每次循环的步长。这就和C语言中的for循环相类似了。 2、enumerate() 利用enumerate()函数,可以在每次循环中同时得到下标和元素: S = 'abcdefghijk'for (index,char) in enumerate(S): print index print char 实际上,enumerate()在每次循环中,返回的是一个包含两个元素的定值表(tuple),两个元素分别赋予index和char 3、zip() 如果你多个等长的序列,然后想要每次循环时从各个序列分别取出一个元素,可以利用zip()方便地实现: ta = [1,2,3]tb = [9,8,7]tc = ['a','b','c']for (a,b,c) in zip(ta,tb,tc): print(a,b,c) 每次循环时,从各个序列分别从左到右取出一个元素,合并成一个tuple,然后tuple的元素赋予给a,b,c zip()函数的功能,就是从多个列表中,依次各取出一个元素。每次取出的(来自不同列表的)元素合成一个元组,合并成的元组放入zip()返回的列表中。zip()函数起到了聚合列表的功能。 我们可以分解聚合后的列表,如下: ta = [1,2,3]tb = [9,8,7]# clusterzipped = zip(ta,tb)print(zipped)# decomposena, nb = zip(*zipped)print(na, nb)三、循环对象 这一讲的主要目的是为了大家在读Python程序的时候对循环对象有一个基本概念。 循环对象的并不是随着Python的诞生就存在的,但它的发展迅速,特别是Python 3x的时代,循环对象正在成为循环的标准形式。 1、什么是循环对象 循环对象是这样一个对象,它包含有一个next()方法(__next__()方法,在python 3x中), 这个方法的目的是进行到下一个结果,而在结束一系列结果之后,举出StopIteration错误。 当一个循环结构(比如for)调用循环对象时,它就会每次循环的时候调用next()方法,直到StopIteration出现,for循环接收到,就知道循环已经结束,停止调用next()。 假设我们有一个test.txt的文件: 1234abcdefg 我们运行一下python命令行: >> > f = open ('test.txt') > f.next () > f.next ().
Keep typing f.next () until StopIteration finally appears
What open () returns is actually a circular object that contains the next () method. The next () method returns the contents of a new line each time, and enumerates StopIteration when it reaches the end of the file. In this way, we are equivalent to a manual loop.
If it is done automatically, it will be as follows:
For line in open ('test.txt'): print line
Here, the for structure automatically calls the next () method, assigning the return value of that method to line. The loop knows that it ends when a StopIteration occurs.
As opposed to sequences, the advantage of using loop objects is that you don't have to generate elements to use before the loop begins. The elements used can be generated one at a time during the loop. In this way, the space is saved, the efficiency is improved, and the programming is more flexible.
2. Iterator
Technically, there is an intermediate layer between the circular object and the for circular call, which is to convert the circular object into an iterator. This conversion is achieved by using the iter () function. But logically, this layer can often be ignored, so loop objects and iterators often refer to each other.
3. Generator
The main purpose of the generator is to form a user-defined loop object.
The generator is written in a way similar to the function definition, except that it is changed to yield in the case of return. There can be multiple yield in the generator. When the generator encounters a yield, it pauses to run the generator and returns the value after the yield. When the generator is called again, it continues to run from where it was paused until the next yield. The generator itself forms a loop, using one value returned by yield at a time.
Here is a generator:
Def gen (): a = 100yield an a = axi8 yield a yield 1000
The generator has three yield, and if used as a circulator, it loops three times.
For i in gen (): print I
Consider the following generator:
Def gen (): for i in range (4): yield I
It can also be written as a generator expression (Generator Expression):
G = (x for x in range (4))
Generator expressions are an easy way to write generators. Readers can refer to it further.
4. Table derivation
Table derivation (list comprehension) is a way to generate tables quickly. Its grammar is simple and has practical value.
Suppose we generate table L:
L = [] for x in range (10): L.append (xylene 2)
The above produces table L, but there is actually a quick way to write it, that is, the way of table derivation:
L = [xylene 2 for x in range (10)]
This is similar to a generator expression, except that it uses square brackets.
(the mechanism of table derivation is actually the use of loop objects, which you can refer to if you are interested. )
This is the end of the content of "detailed introduction of loop functions in Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.