1、使用有名字的切片操作文本文件效率很高。
invoice = """
0.....6.................................40........52...55........
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) #None 表示到最后
line_items = invoice.split('\n')[2:]
for item in line_items:
print(item[UNIT_PRICE], item[DESCRIPTION])
2、...可以作为多维切片的快捷方法,代表该维度全取(:)。
import numpy as np
a=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
a[:,:,1:]
Out[50]:
array([[[ 2, 3],
[ 5, 6]],
[[ 8, 9],
[11, 12]]])
a[...,1:]
Out[52]:
array([[[ 2, 3],
[ 5, 6]],
[[ 8, 9],
[11, 12]]])