## 快速掌握Python中的循环技术

HuangWeiAI 2021-01-21 11:50:38

Python的最基本的循环技术是for语句，它可以遍历任何序列(列表或字符串)中的项目，按照它们在序列中出现的顺序。本文将全面介绍for循环的技术以及实战用法。

1. 使用enumerate()循环整个序列:

```colors=['red','green','blue']
for color in enumerate(colors):
print (color)
#Output:
(0, 'red')
(1, 'green')
(2, 'blue')```

count从5开始循环迭代器。

```colors=['red','green','blue']
for color in enumerate(colors,5):
print (color)
'''
Output:
(5, 'red')
(6, 'green')
(7, 'blue')
'''```

```s='python'
for i in enumerate(s):
print (i)
'''
#Output:
(0, 'p')
(1, 'y')
(2, 't')
(3, 'h')
(4, 'o')
(5, 'n')
'''
```

2. 使用zip()函数循环两个或多个序列:

```num = [1, 2, 3]
colors= ['red', 'blue', 'green']
for i in zip(num, colors):
print(i)
'''
Output:
(1, 'red')
(2, 'blue')
(3, 'green')
''```

```colors=['red','green','blue']
num=[1,2,3,4,5,6,7,8,9,10]
for i in zip(colors,num):
print (i)
'''
Output:
('red', 1)
('green', 2)
('blue', 3)
'''```

```colors=['red','apple','three']
num=[1,2,3]
alp=['a','b','c']
for i in zip(colors,num,alp):
print (i)
'''
Output:
('red', 1, 'a')
('apple', 2, 'b')
('three', 3, 'c')
'''```

3.itertools.zip_longest ()

```from itertools import zip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
for i in zip_longest(colors,num):
print (i)
'''
Output:
('red', 1)
('apple', 2)
('three', 3)
(None, 4)
(None, 5)
'''```

```from itertools import zip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
for i in zip_longest(colors,num,fillvalue='z'):
print (i)
'''
Output:
('red', 1)
('apple', 2)
('three', 3)
('z', 4)
('z', 5)
'''```

4. 使用sorted()函数按已排序的顺序循环序列:

sorted():

```num=[10,5,20,25,30,40,35]
for i in sorted(num):
print (i)
'''
Output:
5
10
20
25
30
35
40
'''```

```num=[10,5,20,25,30,40,35]
for i in sorted(num,reverse=True):
print (i)
'''
Output:
40
35
30
25
20
10
5
'''```

```d={'f':1,'b':4,'a':3,'e':9,'c':2}
for i in sorted(d.items()):
print (i)
#Output:
('a', 3)
('b', 4)
('c', 2)
('e', 9)
('f', 1)```

```d={'f':1,'b':4,'a':3,'e':9,'c':2}
#sorting by values in the dictionary
for i in sorted(d.items(),key=lambda item:item[1]):
print (i)
#Output:
('f', 1)
('c', 2)
('a', 3)
('b', 4)
('e', 9)```

5. 使用reversed()函数遍历序列:

reversed(seq)

```colors=['red','green','blue','yellow']
for i in reversed(colors):
print (i)
'''
Output:
yellow
blue
green
red
'''```

6. 循环查找字典。

```d={'a':1,'b':2,'c':3}
for k,v in d.items():
print (k,v)
#Output:
a 1
b 2
c 3```

7. 在迭代时修改集合:

```d={'a':1,'b':2,'c':3}
for k,v in d.copy().items():
if v%2==0:
del d[k]
print (d)
#Output:{'a': 1, 'c': 3}```

```d={'a':1,'b':2,'c':3}
d1={}
for k,v in d.items():
if v%2!=0:
d1[k]=v
print (d1)
#Output:{'a': 1, 'c': 3}
print (d)
#Output:{'a': 1, 'b': 2, 'c': 3}```

·END·

https://cloud.tencent.com/developer/article/1777093