掌握Python中的循環(huán)技術(shù)
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']
forcolorinenumerate(colors):
print(color)
#Output:
(0,'red')
(1,'green')
(2,'blue')
示例2:
count從5開始循環(huán)迭代器。
colors=['red','green','blue']
forcolorinenumerate(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'
foriinenumerate(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']
foriinzip(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]
foriinzip(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']
foriinzip(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。
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()函數(shù)按已排序的順序循環(huán)序列
sorted():從iterable中的項(xiàng)返回一個(gè)新的排序列表。
示例:1使用sorted()函數(shù)按排序(升序)遍歷序列(list)。
num=[10,5,20,25,30,40,35]
foriinsorted(num):
print(i)
'''
Output:
5
10
20
25
30
35
40
'''
示例2:使用sorted()函數(shù)按排序(降序)遍歷序列(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()函數(shù)按排序(升序)遍歷字典。默認(rèn)情況下,它將對(duì)字典中的鍵進(jìn)行排序。
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:使用已排序的函數(shù)按已排序的順序循環(huán)字典。在已排序的函數(shù)中使用key參數(shù),根據(jù)字典的值對(duì)其排序。
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()函數(shù)遍歷序列
reversed(seq):
返回反向迭代器。seq必須是一個(gè)具有__reversed__()方法或支持序列協(xié)議(__len__()方法和__getitem__()方法,參數(shù)從0開始)的對(duì)象。
示例:
反向循環(huán)一個(gè)序列,然后調(diào)用reversed()函數(shù)。
colors=['red','green','blue','yellow']
foriinreversed(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}
fork,vind.items():
print(k,v)
#Output:
a1
b2
c3
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}
fork,vind.copy().items():
ifv%2==0:
deld[k]
print(d)
#Output:{'a':1,'c':3}
策略2:創(chuàng)建一個(gè)新的集合
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}
以上內(nèi)容為大家介紹了掌握Python中的循環(huán)技術(shù),希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。http://www.mobiletrain.org/

猜你喜歡LIKE
相關(guān)推薦HOT
更多>>
Python如何輸出為文件
python輸出為文件使用withopen()as語(yǔ)句。使用示例:withopen('E:\python\python\test.txt','w')asf:f.writ...詳情>>
2023-11-09 22:08:08
怎么查看python變量的類型
python判斷變量的類型有兩種方法:type()和isinstance()對(duì)于基本的數(shù)據(jù)類型兩個(gè)的效果都一樣type()ip_port=['219.135.164.245',3128...詳情>>
2023-11-09 21:30:21
python如何生成文件夾
python中可以使用os.makedirs()方法創(chuàng)建多級(jí)目錄:os.makedirs()方法用于遞歸創(chuàng)建目錄。像mkdir(),但創(chuàng)建的所有intermediate-level文件夾需要包...詳情>>
2023-11-09 21:11:28
怎樣用python計(jì)算矩陣乘法?
python中計(jì)算矩陣乘法的方法:1、使用np.multiply()函數(shù)計(jì)算矩陣乘法函數(shù)作用:數(shù)組和矩陣對(duì)應(yīng)位置相乘,輸出與相乘數(shù)組/矩陣的大小一致示例:n...詳情>>
2023-11-09 20:01:23熱門推薦
python找不到指定模塊怎么辦
沸python如何將結(jié)果保存
熱python依賴安裝失敗怎么辦
熱怎么把python代碼打包
新Python如何輸出為文件
python如何檢測(cè)字符串是不是全為字母?
怎么查看python變量的類型
python如何生成文件夾
python如何獲取程序執(zhí)行時(shí)間?
Python中猴子補(bǔ)丁是什么?
python字典打印亂碼怎么解決
怎樣用python計(jì)算矩陣乘法?
python如何調(diào)用另一個(gè)文件夾中的內(nèi)容?
python如何去空格和回車?
快速通道 更多>>
-
課程介紹
點(diǎn)擊獲取大綱 -
就業(yè)前景
查看就業(yè)薪資 -
學(xué)習(xí)費(fèi)用
了解課程價(jià)格 -
優(yōu)惠活動(dòng)
領(lǐng)取優(yōu)惠券 -
學(xué)習(xí)資源
領(lǐng)3000G教程 -
師資團(tuán)隊(duì)
了解師資團(tuán)隊(duì) -
實(shí)戰(zhàn)項(xiàng)目
獲取項(xiàng)目源碼 -
開班地區(qū)
查看來校路線