Python字典实现切片操作

这个博客主要介绍了如何在Python中进行字典切片操作,包括处理不同的边界条件,如start和end在可切片范围内以及各种重叠和非重叠情况。函数dictcut接受一个字典和两个下标作为参数,返回一个新的字典,包含原始字典中指定下标范围内的键值对。博客详细阐述了不同情况下的逻辑判断和遍历方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 字典切片
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值