python 字典连续 key提取

目录

python 字典连续 key提取

key和value也提取:

结果:


python 字典连续 key提取

def extract_consecutive_keys(data):
    # 将字典的键按升序排序
    keys = sorted(data.keys())
    consecutive_groups = []
    current_group = [keys[0]]  # 第一个元素开始一个新的组

    # 遍历剩余的键
    for i in range(1, len(keys)):
        if keys[i] == keys[i - 1] + 1:  # 如果当前键与前一个键连续
            current_group.append(keys[i])
        else:  # 如果不连续,开始一个新的组
            consecutive_groups.append(current_group)
            current_group = [keys[i]]

    # 添加最后一组
    consecutive_groups.append(current_group)

    return consecutive_groups


# 示例数据
aaa = {1: 0, 2: 0, 4: 0, 3: 0, 6: 0, 9: 0, 8: 0, 7: 0}

# 提取连续的键
consecutive_keys = extract_consecutive_keys(aaa)

# 打印结果
print(consecutive_keys)

结果:

[[1, 2, 3, 4], [6, 7, 8, 9]]

key和value也提取:

def extract_consecutive_keys(data):
    # 将字典的键按升序排序
    keys = sorted(data.keys())
    consecutive_groups = []
    consecutive_keys=[]
    current_group = [data[keys[0]]]  # 第一个元素开始一个新的组
    current_key = [keys[0]]
    # 遍历剩余的键
    for i in range(1, len(keys)):
        if keys[i] == keys[i - 1] + 1:  # 如果当前键与前一个键连续
            current_group.append(data[keys[i]])
            current_key.append(keys[i])
        else:  # 如果不连续,开始一个新的组
            consecutive_groups.append(current_group)
            consecutive_keys.append(current_key)
            current_group = [data[keys[i]]]
            current_key = [keys[i]]
    # 添加最后一组
    consecutive_groups.append(current_group)
    consecutive_keys.append(current_key)

    return consecutive_keys,consecutive_groups


# 示例数据
aaa = {1: 0, 2: 0, 4: 0, 3: 0, 6: 0, 9: 0, 8: 0, 7: 0}

# 提取连续的键
consecutive_keys,consecutive_groups = extract_consecutive_keys(aaa)

# 打印结果
print(consecutive_keys)
print(consecutive_groups)

结果:

[[1, 2, 3, 4], [6, 7, 8, 9]]
[[0, 0, 0, 0], [0, 0, 0, 0]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值