Python高階特性 一

2021-09-01 18:38:03 字數 476 閱讀 4513

一.切片

l = ['michael', 'sarah', 'tracy', 'bob', 'jack']

取出前三個元素 , 笨方法就是通過下標乙個乙個獲取 [l[0], l[1], l[2]]

python做好了封裝

可以通過切片就行快速獲取

l[0:3] 進行獲取 還可以倒著來 比如l[-2,-1]

取出前幾個 l[:n]

後幾個l[n:]

前幾個每幾個取乙個l[:n:x]

所有數每幾個取乙個l[::x]

其中字串也可以進行切片 例如c#的substring(n,x) 當然tuple也肯定可以.

二.迭代

給list或者tuple進行遍歷 我們叫做迭代

如何判斷乙個物件是否可迭代呢 通過isinstance關鍵字

>>> isinstance('abc', iterable) # str是否可迭代

true

Python高階特性

l csx sarah tracy bob jack print l 0 l 1 l 2 輸出 csx sarah tracy l 0 3 輸出 csx sarah tracy 如果第乙個索引是0,還可以省略 print l 2 輸出 bob jack print l 2 1 輸出 bob d fo...

Python高階特性

python 高階特性 from collections import iterable from collections import iterator 切片 list切片 l list range 100 print l 0 3 取前3個元素 print l 3 取前3個元素 print l 4...

Python高階特性

切片 slice 非常靈活,體現了python的簡便性 1.取乙個list和tuple的部分元素時的簡化操作 l michael sarah tracy bob jack l 0 3 michael sarah tracy 從0開始不包括3,第乙個索引是0可省略,也支援負數按倒數的順序取值,什麼都不...