Slice operation and implement a sliceable object
1. Example of slicing operation
#模式[start:end:step]
"""
其中,第一个数字start表示切片开始位置,默认为0;
第二个数字end表示切片截止(但不包含)位置(默认为列表长度);
第三个数字step表示切片的步长(默认为1)。
当start为0时可以省略,当end为列表长度时可以省略,
当step为1时可以省略,并且省略步长时可以同时省略最后一个冒号。
另外,当step为负整数时,表示反向切片,这时start应该比end的值要大才行。
"""
aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
print (aList[::]) # 返回包含原列表中所有元素的新列表
# [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
print (aList[::-1]) # 返回包含原列表中所有元素的逆序列表
# [17, 15, 13, 11, 9, 7, 6, 5, 4, 3]
print (aList[::2]) # 隔一个取一个,获取偶数位置的元素
# [3, 5, 7, 11, 15]
print (aList[1::2]) # 隔一个取一个,获取奇数位置的元素
# [4, 6, 9, 13, 17]
print (aList[3:6]) # 指定切片的开始和结束位置
# [6, 7, 9]
aList[0:100] # 切片结束位置大于列表长度时,从列表尾部截断、
# [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
aList[100:] # 切片开始位置大于列表长度时,返回空列表
# []
aList[len(aList):] = [9] # 在列表尾部增加元素
# [3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
aList[:0] = [1, 2] # 在列表头部插入元素 (开始位置和结束位置都是0)
# [1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
aList[3:3] = [8] # 在列表中间位置插入元素
# [1, 2, 3, 8, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
aList[:3] = [22, 16] # 替换列表元素,等号两边的列表长度相等(因为替换的元素是从0到2,但只给了2个)
# [22, 16, 8, 4, 5, 6, 7, 9, 11, 13, 15, 17, 9]
aList[3:] = [4, 5, 6] # 等号两边的列表长度也可以不相等(从第三个位置开始到最后)
# [22, 16, 8, 4, 5, 6]
aList[::2] = [0] * 3 # 隔一个修改一个 [0] * 3 ——> [0, 0, 0]
# [0, 16, 0, 4, 0, 6]
aList[::2] = ['a', 'b', 'c'] # 隔一个修改一个
# ['a', 16, 'b', 4, 'c', 6]
aList[::2] = [1,2] # 左侧切片不连续,等号两边列表长度必须相等
# ValueError: attempt to assign sequence of size 2 to extended slice of size 3
aList[:3] = [] # 删除列表中前3个元素
# [4, 'c', 6]
del aList[:2] # 切片元素连续 (删除列表中0到1的元素)
# [6]
del aList[::2] # 切片元素不连续,隔一个删一个
# ['c']
del aList[::1] # 删除整个列表
# []
2. Implement a sliceable object
Suppose we want to implement an immutable sequence object (Group class), just refer to the structure abc
in the MutableSequence
class in the module .
Refer abc
to the Sequence
classes in the module to implement variable sequences .
__getitem__
Magic is the key function can be sliced, there is no magic in this program will function error: TypeError: 'Group' object is not iterable
.
import numbers
class Group:
#支持切片操作
def __init__(self, group_name, company_name, staffs):
self.group_name = group_name
self.company_name = company_name
self.staffs = staffs
def __reversed__(self):
self.staffs.reverse()
def __getitem__(self, item):
cls = type(self)
if isinstance(item, slice): #如果传进来的是切片类型
return cls(group_name=self.group_name, company_name=self.company_name, staffs=self.staffs[item]) #返回Group类型
elif isinstance(item, numbers.Integral): #如果item是整数 group[0]
return cls(group_name=self.group_name, company_name=self.company_name, staffs=[self.staffs[item]])
def __len__(self):
return len(self.staffs)
def __iter__(self):
return iter(self.staffs)
def __contains__(self, item):
if item in self.staffs:
return True
else:
return False
staffs = ["bobby1", "ming", "bobby2", "bobby3"]
group = Group(company_name="my", group_name="user", staffs=staffs)
reversed(group)
# print(group[0:2]) # <__main__.Group object at 0x00000208FA1EA588>
# print(group[0]) # <__main__.Group object at 0x00000208FA1EA588>
# print(leb(group)) # 4
# if 'ming' in group:
# print('yes')
# yes
for user in group:
print(user)
# bobby3
# bobby2
# ming
# bobby1