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")
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('')
印刷品:
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
序列后面的方括号表示索引或切片,具体取决于括号内的内容:
这两种情况都由序列的
__getitem__()
方法(如果在等号的左边,则为__setitem__()
)处理。索引或切片作为单个参数传递给方法,Python的方法是将切片符号(在本例中为1:10:2
)转换为切片对象:slice(1,10,2)
。因此,如果要定义自己的序列类,或者重写另一个类的
__getitem__
、__setitem__
、或__delitem__
方法,则需要测试索引参数,以确定它是int
还是slice
,并相应地处理:一个
slice
对象有三个属性:start
、stop
和step
,还有一个方法:indices
,它接受一个参数,即对象的长度,并返回一个3元组:(start, stop, step)
。通过调用slice创建一个slice,使用的字段与执行[start:end:step]表示法时使用的字段相同:
要使用切片,只需将其作为索引传递到列表或字符串中:
假设您有一个固定长度文本字段的文件。您可以定义一个切片列表,以便轻松地从该文件中的每个“记录”中提取值。
印刷品:
相关问题 更多 >
编程相关推荐