1.使用enumerate()循環整個序列
當循環遍歷一個序列(如列表、元組、范圍對象、字符串)時,可以使用enumerate()函數同時檢索位置索引和相應的值。
(1)使用enumerate()遍歷列表:
示例1:
使用enumerate()函數遍歷列表,返回一個包含可迭代對象中的計數和值的元組。一般情況下,計數從0開始。
colors=['red','green','blue']
forcolorinenumerate(colors):
print(color)
#Output:
(0,'red')
(1,'green')
(2,'blue')
示例2:
count從5開始循環迭代器。
colors=['red','green','blue']
forcolorinenumerate(colors,5):
print(color)
'''
Output:
(5,'red')
(6,'green')
(7,'blue')
'''
(2)使用enumerate()循環字符串:
示例:
使用enumerate()函數遍歷字符串將返回一個包含可迭代對象的計數和值的元組。一般情況下,計數從0開始。
s='python'
foriinenumerate(s):
print(i)
'''
#Output:
(0,'p')
(1,'y')
(2,'t')
(3,'h')
(4,'o')
(5,'n')
'''
2.使用zip()函數循環兩個或多個序列
要同時循環兩個或多個序列,可以使用zip()函數對條目進行配對。
(1)使用zip()循環兩個相同長度的序列
示例:
num=[1,2,3]
colors=['red','blue','green']
foriinzip(num,colors):
print(i)
'''
Output:
(1,'red')
(2,'blue')
(3,'green')
''
(2)使用zip()循環兩個不同長度的序列
如果使用zip()遍歷兩個長度不同的序列意味著當最短的可迭代對象耗盡時停止。
示例:
colors=['red','green','blue']
num=[1,2,3,4,5,6,7,8,9,10]
foriinzip(colors,num):
print(i)
'''
Output:
('red',1)
('green',2)
('blue',3)
'''
(3)使用zip()循環兩個或多個序列:
示例:
colors=['red','apple','three']
num=[1,2,3]
alp=['a','b','c']
foriinzip(colors,num,alp):
print(i)
'''
Output:
('red',1,'a')
('apple',2,'b')
('three',3,'c')
'''
3.itertools.zip_longest()
創建一個從每個可迭代對象中聚合元素的迭代器。如果可迭代對象的長度不均勻,則用fillvalue填充缺失的值。迭代繼續,直到最長的可迭代對象耗盡。
使用itertools.zip_longest()循環兩個不同長度的序列。
示例1:如果不指定fillvalue,則默認為None。
fromitertoolsimportzip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
foriinzip_longest(colors,num):
print(i)
'''
Output:
('red',1)
('apple',2)
('three',3)
(None,4)
(None,5)
'''
示例2:指定fillvalue。
fromitertoolsimportzip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
foriinzip_longest(colors,num,fillvalue='z'):
print(i)
'''
Output:
('red',1)
('apple',2)
('three',3)
('z',4)
('z',5)
'''
4.使用sorted()函數按已排序的順序循環序列
sorted():從iterable中的項返回一個新的排序列表。
示例:1使用sorted()函數按排序(升序)遍歷序列(list)。
num=[10,5,20,25,30,40,35]
foriinsorted(num):
print(i)
'''
Output:
5
10
20
25
30
35
40
'''
示例2:使用sorted()函數按排序(降序)遍歷序列(list)。
num=[10,5,20,25,30,40,35]
foriinsorted(num,reverse=True):
print(i)
'''
Output:
40
35
30
25
20
10
5
'''
示例3:使用sorted()函數按排序(升序)遍歷字典。默認情況下,它將對字典中的鍵進行排序。
d={'f':1,'b':4,'a':3,'e':9,'c':2}
foriinsorted(d.items()):
print(i)
#Output:
('a',3)
('b',4)
('c',2)
('e',9)
('f',1)
示例4:使用已排序的函數按已排序的順序循環字典。在已排序的函數中使用key參數,根據字典的值對其排序。
d={'f':1,'b':4,'a':3,'e':9,'c':2}
#sortingbyvaluesinthedictionary
foriinsorted(d.items(),key=lambdaitem:item[1]):
print(i)
#Output:
('f',1)
('c',2)
('a',3)
('b',4)
('e',9)
5.使用reversed()函數遍歷序列
reversed(seq):
返回反向迭代器。seq必須是一個具有__reversed__()方法或支持序列協議(__len__()方法和__getitem__()方法,參數從0開始)的對象。
示例:
反向循環一個序列,然后調用reversed()函數。
colors=['red','green','blue','yellow']
foriinreversed(colors):
print(i)
'''
Output:
yellow
blue
green
red
'''
6.循環查找字典
當循環遍歷字典時,可以使用items()方法同時檢索鍵和相應的值。
示例:
d={'a':1,'b':2,'c':3}
fork,vind.items():
print(k,v)
#Output:
a1
b2
c3
7.在迭代時修改集合
在遍歷同一個集合時修改集合的代碼可能很難正確處理。相反,循環遍歷集合的副本或創建一個新集合通常更簡單。
策略1:對副本進行迭代
如果希望在迭代時刪除字典中的項,則在字典的副本上進行迭代:
d={'a':1,'b':2,'c':3}
fork,vind.copy().items():
ifv%2==0:
deld[k]
print(d)
#Output:{'a':1,'c':3}
策略2:創建一個新的集合
d={'a':1,'b':2,'c':3}
d1={}
fork,vind.items():
ifv%2!=0:
d1[k]=v
print(d1)
#Output:{'a':1,'c':3}
print(d)
#Output:{'a':1,'b':2,'c':3}
以上內容為大家介紹了掌握Python中的循環技術,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。http://www.dietsnews.net/