Python字典实现切片操作

# 字典切片
def dictcut(dict, start, end):
    # 临时存放字典的key
    temp = list(dict.keys())
    # 返回一个字典
    result = {}
    # 分两个分支 1.start和end在可切片范围内 2.不在范围内
    if start <= len(temp) - 1 and start >= -len(temp) and end <= len(temp) - 1 and end >= -len(temp):
        # start大于end,且下标不重叠
        if start > end and start - 1 != len(temp) + end:
            # start和end同时为大于等于0
            if start >= 0 and end >= 0:
                # (4,2) 4 0 1
                for i in range(start, len(temp)):
                    result[temp[i]] = dict.get(temp[i])
                for i in range(0, end):
                    result[temp[i]] = dict.get(temp[i])
            # start和end同时小等于0
            if start <= 0 and end <= 0:
                # (-1,-3) 4 0 1
                for i in range(len(temp) + start, len(temp)):
                    result[temp[i]] = dict.get(temp[i])
                for i in range(0, len(temp) + end):
                    result[temp[i]] = dict.get(temp[i])
            # start大于0,end小于0
            if start >= 0 and end < 0:
                # (1,-2) 1 2
                for i in range(start, len(temp) + end):
                    result[temp[i]] = dict.get(temp[i])

        # end大于start,且下标不重叠
        elif end > start and start + len(temp) != end - 1:
            # start和end同时为大于等于0
            if start >= 0 and end >= 0:
                # (0,3) 0 1 2
                for i in range(start, end):
                    result[temp[i]] = dict.get(temp[i])
            # start和end同时大小等于0
            if start <= 0 and end <= 0:
                # (-4,-1) 1 2 3
                for i in range(len(temp) + start, len(temp) + end):
                    result[temp[i]] = dict.get(temp[i])
            # end大等于0,start小于0
            if end >= 0 and start < 0:
                # (-1,3) 4 0 1 2
                for i in range(len(temp) + start, len(temp)):
                    result[temp[i]] = dict.get(temp[i])
                for i in range(end):
                    result[temp[i]] = dict.get(temp[i])
        # start等于end,或者下标重叠
        elif end == start or start + len(temp) == end - 1 or end <= 0 and start - 1 == len(temp) + end:
            print("切了个寂寞!")
    # start或者end不在范围内
    else:
        print("传入参数有误!")
    return result

你可能感兴趣的:(python,numpy,开发语言)