我在 python 中为字典切片制作了一个示例代码......如果您有任何其他想法要添加,请告诉我[关闭]

问题描述 投票:0回答:1

在 Python 中,我们知道字典没有切片。我该怎么做?

python dictionary slice
1个回答
-2
投票

这是我的代码:

def my_dict_slice(dict, start, end, step=None):
    new_dict = {}
    if not step:
        step = 1
    step_continue = step
    index = start
    index_continue = 0
    for idx, item in enumerate(dict.items()):
        if index != 0 and index_continue != start:
            index_continue += 1
            continue
        if start <= index < end:
            if step != 1:
                if step_continue == step:
                    new_dict[item[0]] = item[1]
                    index += step
                    step_continue = 1
                else:
                    step_continue += 1
                    continue
            else:
                new_dict[item[0]] = item[1]
                index += step
    return new_dict

我找到了一个很好的解决方案:

dict(list(my_dict.items())[start:end:step])
© www.soinside.com 2019 - 2024. All rights reserved.