問題:那些物件支援遍歷?
答:可迭代的物件支援遍歷
方法:(1)next()函式
(2)全域性呼叫next()函式
(1)說明可遍歷物件(列表,元組,字典表,檔案),可迭代的物件支援遍歷。
#列表遍歷
for x in [1,2,3]:
print(x)
#元組遍歷
for y in (1,2,3):
print(y)
#字典表(只能詢問單獨的鍵或值)
info =
for key in info:
print(key)
for value in info:
print(value)
#檔案遍歷
f = open('data.txt','r',encoding = 'utf-8')
for line in f:
print(line,end = ' ')
(2)迭代協議示例next()和next()
next()的作用是呼叫一行,再呼叫一行,直到停止迭代,停止遍歷
next()定義全域性迭代函式
迭代的優勢:相當於進棧和出棧,所佔記憶體空間小
f = open('data.txt','r',encoding = 'utf-8')
f.__next__()
out[3]: 'june\n'
f.__next__()
out[4]: 'python學習\n'
f.__next__()
out[5]: 'fighting\n'
f = open('data.txt','r',encoding = 'utf-8')
next(f)
out[4]: 'june\n'
(3)判斷是否本身具備迭代功能
iter(列表) is 列表 (列表屬於可迭代物件)
i = iter(liebiao) (將本身不能生成迭代器的生成迭代器)
iter(檔案) is 檔案 (檔案屬於迭代其物件)
r = range(1,6)
iter(r) is r
out[3]: false
i = iter(r)
next(i)
out[5]: 1
next(i)
out[6]: 2
f = open('data.txt','r')
iter(f) is f
out[3]: true
(4)推導:返回乙個列表中所有元素的平方值
l = [1,2,3,4,5]
rest1 = [x for x in l]
print(rest1)
rest2 = [x+10 for x in l]
print(rest2)
rest3 = [x**2 for x in l]
print(rest3)
(5)range內建可迭代物件
result = [x**2 for x in range(1,6)]
print(result)
[1, 4, 9, 16, 25]
r = range(1,6)
iter(r) is r
out[5]: false
i = iter(r)
iter(i) is i
out[7]: true
stopiteration
out[8]: stopiteration
(6)zip壓縮屬於迭代器物件,將兩個或多個合成乙個
result = zip(['x','y','z'],[1,2,3])
print(result)
result.__next__()
out[4]: ('x', 1)
result.__next__()
out[5]: ('y', 2)
result.__next__()
out[6]: ('z', 3)
iter(result) is result
out[7]: true
(7)map屬於迭代器物件
是python內建的高階函式,接收乙個函式f和乙個list,並通過函式f一次作用在list的每個元素上,得到乙個新的object並返回
map(f(x),itera)
def double_number(x):
return x * 2
#map返回乙個object,因為map()轉換成迭代器來節約空間,可用list強制返回為列表
l = [1,2,3,4,5]
result = list(map(double_number,l))
print(result)
python基礎 迭代
在python中,迭代通過 for.in完成,如 for ch in abc print ch ab c判斷乙個物件是否是可迭代物件 collections模組的iterable型別 from collections import iterable isinstance abc iterable t...
Python基礎(迭代)
from collections import iterable collections模組的iterable型別判斷 dict1 print dict1.keys dict keys a b c print dict1.values dict values 111,222,333 print di...
Python基礎學習四 for迴圈,函式,迭代器
for 變數 in 序列 執行的 塊 list01 joe susan jack tom 遍歷列表 for i in list01 print i pass空操作,無任何意義,pass語句的使用表示不希望任何 或命令的執行 pass語句是乙個空操作,在執行的時候不會產生任何反應 pass語句常出現在...