内置函数slice的用途是什么?我如何使用它?
我所知道的毕达通切片的直接方法- l1[start:stop:step]。我想知道我是否有一个片对象,那么我如何使用它呢?
发布于 2010-10-12 04:43:17
通过使用与执行start:end:step表示法使用的相同字段调用片来创建一个片:
sl = slice(0,4)要使用该切片,只需将其作为索引传递到列表或字符串中:
>>> s = "ABCDEFGHIJKL"
>>> sl = slice(0,4)
>>> print(s[sl])
'ABCD'假设您有一个固定长度文本字段的文件。您可以定义一个切片列表,以方便地从该文件中的每个“记录”中提取值。
data = """\
0010GEORGE JETSON 12345 SPACESHIP ST HOUSTON TX
0020WILE E COYOTE 312 ACME BLVD TUCSON AZ
0030FRED FLINTSTONE 246 GRANITE LANE BEDROCK CA
0040JONNY QUEST 31416 SCIENCE AVE PALO ALTO CA""".splitlines()
fieldslices = [slice(*fielddef) for fielddef in [
(0,4), (4, 21), (21,42), (42,56), (56,58),
]]
fields = "id name address city state".split()
for rec in data:
for field,sl in zip(fields, fieldslices):
print("{} : {}".format(field, rec[sl]))
print('')
# or this same code using itemgetter, to make a function that
# extracts all slices from a string into a tuple of values
import operator
rec_reader = operator.itemgetter(*fieldslices)
for rec in data:
for field, field_value in zip(fields, rec_reader(rec)):
print("{} : {}".format(field, field_value))
print('')指纹:
id : 0010
name : GEORGE JETSON
address : 12345 SPACESHIP ST
city : HOUSTON
state : TX
id : 0020
name : WILE E COYOTE
address : 312 ACME BLVD
city : TUCSON
state : AZ
id : 0030
name : FRED FLINTSTONE
address : 246 GRANITE LANE
city : BEDROCK
state : CA
id : 0040
name : JONNY QUEST
address : 31416 SCIENCE AVE
city : PALO ALTO
state : CA发布于 2010-10-12 06:16:45
序列后面的方括号表示索引或切片,具体取决于括号内的内容:
>>> "Python rocks"[1] # index
'y'
>>> "Python rocks"[1:10:2] # slice
'yhnrc'这两种情况都由序列的__getitem__()方法处理(如果位于等号的左边,则为__setitem__() )。索引或切片作为单个参数传递给方法,Python的方法是将片表示法(在本例中为1:10:2)转换为片对象:slice(1,10,2)。
因此,如果要定义自己的类似序列的类,或者重写另一个类的__getitem__或__setitem__或__delitem__方法,则需要测试索引参数以确定它是int还是slice,并相应地进行处理:
def __getitem__(self, index):
if isinstance(index, int):
... # process index as an integer
elif isinstance(index, slice):
start, stop, step = index.indices(len(self)) # index is a slice
... # process slice
else:
raise TypeError("index must be int or slice")slice对象有三个属性:start、stop和step,还有一个方法:indices,它接受一个参数,对象的长度,并返回一个3元组:(start, stop, step)。
发布于 2010-10-12 06:20:48
>>> class sl:
... def __getitem__(self, *keys): print keys
...
>>> s = sl()
>>> s[1:3:5]
(slice(1, 3, 5),)
>>> s[1:2:3, 1, 4:5]
((slice(1, 2, 3), 1, slice(4, 5, None)),)
>>>https://stackoverflow.com/questions/3911483
复制相似问题