Python basis | those things about the "cycle"

Python common cycle there are two types :

  • for
  • while

for loop

list

listIt is the most common iterable, other iterations of objects such as dict, set, File Lines, stringetc.

for i in set((1,2,3)):
    print(i)

Output:
. 1
2
. 3

import string

list_num = list(string.digits)

for i in list_num:
    # 输出偶数
    if int(i)%2 == 0:
        print(i)

Output:
0
2
. 4
. 6
. 8

range

Range 有头无尾, EG range(1,3)sequence is actually obtained(1,2)

for i in range(3):
    print(i)

Output:
0
. 1
2

for i in range(1,9):
    # 输出偶数
    if int(i)%2 == 0:
        print(i)

Output:
2
. 4
. 6
. 8

enumerate

enumeratePlus index for the circulation of the list, the index is numbered starting from 0

list_val = [1,2,3,5,8]
for idx,val in enumerate(list_val):
    print(idx,val)

Output:
0. 1
. 1 2
2. 3
. 3. 5
. 4. 8

zip

Simultaneously traverse two or more list, press packing order

list_1 = string.digits[:3]
list_2 = string.ascii_lowercase[:3]
list_3 = string.ascii_uppercase[:3]

print(list_1,list_2,list_3)

Output:
012 abc ABC

list_merge_1 = list(zip(list_1,list_2,list_3))
print(list_merge_1)

list_merge_2 = [i+j+k for (i,j,k) in zip(list_1,list_2,list_3)]
print(list_merge_2)

Output:
[( '0', 'A', 'A'), ( '. 1', 'B', 'B'), ( '2', 'C', 'C')]
[ '0AA', '1bB', '2cC']

# 元素组合
list_merge_3 = [i+j for i in list('123') for j in list('ABC')]

print(list_merge_3)

Output:
[ '. 1A', '. IB', '1C', '. 2A', '2B', '2C', '. 3A', '3B', '. 3C']

while loop

while equivalent for and if the combination.

while the cycle is not necessarily performed, and if sometimes function almost equivalent to the meaning of this time while如果条件为真,那就执行如下操作

while playing the role for more and if combined, the equivalent of重复执行如下操作,知道判断条件(会不断变化)不再成立为止

While if the time equivalent

# 需要break的配合
x = 2

while(x>1):
    print('这个值大于1')
    
    break

Output:
This value is greater than 1

while acting as a mixture of for and if the

# 需要自增的index来配合

idx = 1

while(idx < 5):
    print(idx)
    
    idx += 1

Output:
. 1
2
. 3
. 4

Pan-cycle

If the loop is understood as a sequence of traversal order.
Except for, while you can also reach the "walk" effect with other functions.

List comprehension

Or the nature of the cycle, common for loop statement is reflected in the multi-line, and 列表解析a line of

# 筛选奇数
num_odd = [i for i in range(1,10) if i%2==1]

print(num_odd)

Output:
[1, 3, 5, 7, 9]

map

Do the same for the plurality of objects in sequence

list(map(lambda x:x**2,range(4)))

Output:
[0, 1, 4, 9]

list_words = ['life','is','short','use','python']

list(map(lambda x:len(x),list_words))

Output:
[4, 2, 5, 3, 6]

Iterator

Variant of the for loop

The sequence order value a "pop-up", while the "pop" out of sequence value

Sequence is empty, an errorStopIteration

vals_iter = iter(list(range(3)))

next(vals_iter)

Output:
0

Iteration may be as exemplified above as "finite" iteration, may be "infinite", such as the self-energizing sequence (index natural order)

# 定义一个迭代器
class test_iter:
    def __init__(self):
        self.a = 1
        self.b = 1
        
    def __iter__(self):
        return self
 
    def __next__(self):
        x = self.a
        self.a, self.b = self.b, self.a+self.b
        return x
fb = test_iter()

for i in range(6):
    print(next(fb))

Output:
. 1
. 1
2
. 3
. 5
. 8

Builder

Comparative generators and iterator

Same point:

  • See all "iteration" generate a sequence based on certain rules from the implementation of the results (whether it is "endless" series or "finite" series)
  • Support iter, next method
  • After the "pop-up" value, it will clear the "pop-up" value

difference:

  • Generator belongs iterator
  • When the definition, 生成器it functions as natural and definition (iter simultaneously and automatically generate the next method), defined mainly by the iterator iter, next defined sequence;
  • More Reference 1
  • More Reference 2
def num_even(x):
    while(x>0):
        if x%2 == 0:
            yield x
        x -= 1
x = num_even(9)

for i in x:
    print(i)

Output:
. 8
. 6
. 4
2

Loop jump out and continue

breakIs out of the loop , i.e. the loop are no longer performed, if the nested loop, the loop is also terminated the upper

continue Skip the current operation into the next cycle , no effect on the upper loop

pass Then execution, with very little, do not speak here

break, continue after the statement is not executed, so be sure to note the location of these two keywords placed

Single-cycle

for i in range(5):
    print(i)
    
    if i == 2:
        break # 当i=2时,循环结束
        print('不会出现')   

Output:
0
. 1
2

for i in range(5):
    
    if i == 2:
        continue # 跳过2这个值
        print('不会出现')   
    print(i)

Output:
0
. 1
. 3
. 4

i = 1
while(i<5):
    print(i)
    break # 执行一次就结束
    print('不会出现')   

Output:
1

i = 1
while(i<5):
    print(i)
    
    i += 1
    if i == 2:
        continue
        print('不会出现')   
    

Output:
. 1
2
. 3
. 4

while with continue to be careful ah, such as the following code will always be executed

i = 1
while(i<5):
    print(i)
    
    if i == 2:
        continue
        print('不会出现') 
        
    i += 1

Nested loop

for i in range(3):
    for j in list('abc'):
        if j == 'b':
            break # 到b的时候就停止了
        print(i,j)

Export:
0 A
1 A
2 A

for i in range(3):
    for j in list('abc'):
        if i == 1 or j=='b':
            continue
        print(i,j) #不会出现带1和b的输出值

Output:
0 A
0 C
2 A
2 C

Guess you like

Origin www.cnblogs.com/dataxon/p/12563843.html