在Python 里,像列表(list)、元組(tuple)和字符串(str)這類(lèi)序列類(lèi)型都支持切片操作框杜,但是實(shí)際上切片操作比我們所想象的要強(qiáng)大很多。下面是一些切片形式的用法袖肥。
對(duì)對(duì)象進(jìn)行切片
>>> s = 'bicycle'
>>> s[::3]
'bye'
>>> s[::-1]
'elcycib'
>>> s[::-2]
'eccb'
a:b:c
這種用法只能作為索引或者下標(biāo)用在 [] 中來(lái)返回一個(gè)切片對(duì)象:slice(a, b, c)
咪辱。對(duì) seq[start:stop:step]
進(jìn)行求值的時(shí)候,Python 實(shí)際上會(huì)調(diào)用seq.__getitem__(slice(start, stop, step))
。
下面純文本文件形式的收據(jù)以一行字符串的形式被解析
invoice = """
1909 Pimoroni PiBrella $17.50 3 $52.50
1489 6mm Tactile Switch x20 $4.95 2 $9.90
1510 Panavise Jr. - PV-201 $28.00 1 $28.00
1601 PiTFT Mini Kit 320x240 $34.95 1 $34.95
"""
SKU = slice(0, 6)
DESCRIPTION = slice(6, 40)
UNIT_PRICE = slice(40, 52)
QUANTITY = slice(52, 55)
ITEM_TOTAL = slice(55, None)
line_items = invoice.split('\n')
for item in line_items:
print(item[UNIT_PRICE], item[DESCRIPTION])
$17.50 Pimoroni PiBrella
$4.95 6mm Tactile Switch x20
$28.00 Panavise Jr. - PV-201
$34.95 PiTFT Mini Kit 320x240
對(duì)切片賦值
如果把切片放在賦值語(yǔ)句的左邊椎组,或把它作為 del 操作的對(duì)象油狂,我們就可以對(duì)序列進(jìn)行嫁接、切除或就地修改操作寸癌。
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[2:5] = [20, 30]
>>> l
[0, 1, 20, 30, 5, 6, 7, 8, 9]
>>> del l[5:7]
>>> l
[0, 1, 20, 30, 5, 8, 9]
>>> l[3::2] = [11, 22]
>>> l