return self.data[index]else: msg = "{cls.__name__} indices must be integers"raise TypeError(msg.format(cls=cls))l = MyList(["My", "name", "is", "Python猫"])### 输出结果:key is : 3Python猫key is : slice(None, 2, None)data is : ['My', 'name']<__main__.MyList ...
官方文档释义:Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to themethod. If key is of an inappropriate t...
slice_object = slice(1, 6, 2) print(py_string[slice_object]) # yhn Output Pyt yhn Example 3: Get substring using negative index py_string = 'Python' # start = -1, stop = -4, step = -1 # contains indices -1, -2 and -3 slice_object = slice(-1, -4, -1) print(py_strin...
self.data = anylistdef__len__(self):returnlen(self.data)def__getitem__(self, index):print("key is : "+str(index)) cls =type(self)ifisinstance(index,slice):print("data is : "+str(self.data[index]))returncls(self.data[index])elifisinstance(index, numbers.Integral):returnself.data[...
returnself.data[index] else: msg ="{cls.__name__} indices must be integers" raiseTypeError(msg.format(cls=cls)) l = MyList(["My","name","is","Python猫"]) ### 输出结果: keyis:3 Python猫 keyis: slice(None,2,None) datais: ['My','name'...
return self.data[index] else: msg = "{cls.__name__} indices must be integers" raise TypeError(msg.format(cls=cls)) l = MyList(["My", "name", "is", "Python猫"]) ### 输出结果: key is : 3 Python猫 key is : slice(None, 2, None) ...
li[::0] # 报错(ValueError: slice step cannot be zero) 上述的某些例子对于初学者(甚至很多老手)来说,可能还不好理解,但是它们都离不开切片的基本语法,所以为方便起见,我将它们也归入基础用法中。 对于这些样例,我个人总结出两条经验: (1)牢牢记住公式[i : i+n : m],当出现缺省值时,通过想象把公式补...
.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(
Called to implement evaluation ofself[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the__getitem__()method. Ifkeyis of an inappropriate type...
# Makefile示例run:python3 slice_example.py 1. 2. 3. # slice_example.py 示例代码my_list=[1,2,3,4,5]# 正向切片positive_slice=my_list[1:4]print("正向切片:",positive_slice)# 反向切片negative_slice=my_list[-3:-1]print("反向切片:",negative_slice) ...