Discuss / Python / 用循环实现列表切片的常用用法

用循环实现列表切片的常用用法

Topic source

不是很成熟,,实现了测试里面切片的一些用法

class Slice_List_Test:
    def __init__(self, a=0, b=10):
        self.l = list(range(a, b))
    def __getitem__(self, n):
        if isinstance(n, slice):
            # 处理start、stop、step参数
            start = n.start
            stop = n.stop
            step = n.step
            if start == None:
                start = 0
            elif start < 0:
                start = len(self.l) + start 
            if stop == None:
                stop = len(self.l) 
            elif stop < 0:
                stop = len(self.l) + stop 
            if step == None:
                step = 1
            elif step == 0:
                raise ValueError('Step cannot be zero')
            result = []
            if step < 0:
                if start > stop:
                    start, stop = stop, start
                # print(start == 0)
                # print(stop == len(self.l) 
                if start != 0 and stop != len(self.l):
                    start += 1
                    stop += 1
            # 迭代取值
            t = 0
            for n in self.l:
                if (start <= t < stop) and ((t - start) % step == 0):
                    if step > 0:
                        result.append(n)
                    else:
                        result.insert(0, n)
                t += 1
            # print(result)
            return result
# 测试
l = list(range(0, 10))
a = Slice_List_Test()
print(a[:] == l[:])
print(a[::-1] == l[::-1])
print(a[2:] == l[2:])
print(a[:5] == l[:5])
print(a[1:5] == l[1:5])
print(a[1:5:2] == l[1:5:2])
print(a[-5:-1] == l[-5:-1])
print(a[-2:-4:-1] == l[-2:-4:-1])
print(a[-2:-7:-2] == l[-2:-7:-2])

  • 1

Reply