快速掌握Python中的循環(huán)技術(shù)
Python的最基本的循環(huán)技術(shù)是for語(yǔ)句,它可以遍歷任何序列(列表或字符串)中的項(xiàng)目,按照它們?cè)谛蛄兄谐霈F(xiàn)的順序。本文將全面介紹for循環(huán)的技術(shù)以及實(shí)戰(zhàn)用法。
1. 使用enumerate()循環(huán)整個(gè)序列
當(dāng)循環(huán)遍歷一個(gè)序列(如列表、元組、范圍對(duì)象、字符串)時(shí),可以使用enumerate()函數(shù)同時(shí)檢索位置索引和相應(yīng)的值。
(1) 使用enumerate()遍歷列表:
示例1:
使用enumerate()函數(shù)遍歷列表,返回一個(gè)包含可迭代對(duì)象中的計(jì)數(shù)和值的元組。一般情況下,計(jì)數(shù)從0開始。
- colors=['red','green','blue']
- for color in enumerate(colors):
- print (color)
- #Output:
- (0, 'red')
- (1, 'green')
- (2, 'blue')
示例2:
count從5開始循環(huán)迭代器。
- colors=['red','green','blue']
- for color in enumerate(colors,5):
- print (color)
- '''
- Output:
- (5, 'red')
- (6, 'green')
- (7, 'blue')
- '''
(2) 使用enumerate()循環(huán)字符串:
示例:
使用enumerate()函數(shù)遍歷字符串將返回一個(gè)包含可迭代對(duì)象的計(jì)數(shù)和值的元組。一般情況下,計(jì)數(shù)從0開始。
- s='python'
- for i in enumerate(s):
- print (i)
- '''
- #Output:
- (0, 'p')
- (1, 'y')
- (2, 't')
- (3, 'h')
- (4, 'o')
- (5, 'n')
- '''
2. 使用zip()函數(shù)循環(huán)兩個(gè)或多個(gè)序列
要同時(shí)循環(huán)兩個(gè)或多個(gè)序列,可以使用zip()函數(shù)對(duì)條目進(jìn)行配對(duì)。
(1) 使用zip()循環(huán)兩個(gè)相同長(zhǎng)度的序列
示例:
- num = [1, 2, 3]
- colors= ['red', 'blue', 'green']
- for i in zip(num, colors):
- print(i)
- '''
- Output:
- (1, 'red')
- (2, 'blue')
- (3, 'green')
- ''
(2) 使用zip()循環(huán)兩個(gè)不同長(zhǎng)度的序列
如果使用zip()遍歷兩個(gè)長(zhǎng)度不同的序列意味著當(dāng)最短的可迭代對(duì)象耗盡時(shí)停止。
示例:
- 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)
- '''
(3) 使用zip()循環(huán)兩個(gè)或多個(gè)序列:
示例:
- 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 ()
創(chuàng)建一個(gè)從每個(gè)可迭代對(duì)象中聚合元素的迭代器。如果可迭代對(duì)象的長(zhǎng)度不均勻,則用fillvalue填充缺失的值。迭代繼續(xù),直到最長(zhǎng)的可迭代對(duì)象耗盡。
使用itertools.zip_longest()循環(huán)兩個(gè)不同長(zhǎng)度的序列。
示例1:如果不指定fillvalue,則默認(rèn)為None。
- 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)
- '''
示例2:指定fillvalue。
- 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()函數(shù)按已排序的順序循環(huán)序列
sorted():從iterable中的項(xiàng)返回一個(gè)新的排序列表。
示例:1使用sorted()函數(shù)按排序(升序)遍歷序列(list)。
- num=[10,5,20,25,30,40,35]
- for i in sorted(num):
- print (i)
- '''
- Output:
- 5
- 10
- 20
- 25
- 30
- 35
- 40
- '''
示例2:使用sorted()函數(shù)按排序(降序)遍歷序列(list)。
- 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
- '''
示例3:使用sorted()函數(shù)按排序(升序)遍歷字典。默認(rèn)情況下,它將對(duì)字典中的鍵進(jìn)行排序。
- 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)
示例4:使用已排序的函數(shù)按已排序的順序循環(huán)字典。在已排序的函數(shù)中使用key參數(shù),根據(jù)字典的值對(duì)其排序。
- 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()函數(shù)遍歷序列
reversed(seq):
返回反向迭代器。seq必須是一個(gè)具有__reversed__()方法或支持序列協(xié)議(__len__()方法和__getitem__()方法,參數(shù)從0開始)的對(duì)象。
示例:
反向循環(huán)一個(gè)序列,然后調(diào)用reversed()函數(shù)。
- colors=['red','green','blue','yellow']
- for i in reversed(colors):
- print (i)
- '''
- Output:
- yellow
- blue
- green
- red
- '''
6. 循環(huán)查找字典
當(dāng)循環(huán)遍歷字典時(shí),可以使用items()方法同時(shí)檢索鍵和相應(yīng)的值。
示例:
- d={'a':1,'b':2,'c':3}
- for k,v in d.items():
- print (k,v)
- #Output:
- a 1
- b 2
- c 3
7. 在迭代時(shí)修改集合
在遍歷同一個(gè)集合時(shí)修改集合的代碼可能很難正確處理。相反,循環(huán)遍歷集合的副本或創(chuàng)建一個(gè)新集合通常更簡(jiǎn)單。
策略1:對(duì)副本進(jìn)行迭代
如果希望在迭代時(shí)刪除字典中的項(xiàng),則在字典的副本上進(jìn)行迭代:
- 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}
策略2:創(chuàng)建一個(gè)新的集合
- 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}
英文原文鏈接:
https://medium.com/analytics-vidhya/looping-techniques-in-python-3bbf907b8dfa