首页 > 解决方案 > Python 字典 - 值子列表

问题描述

我有一本字典。

我需要以这样的方式将值映射到键,即每个子列表映射应该相差 3。

给定的字典是:

{
    8: [3, 4, 5, 6,9, 11, 12, 13, 14,15,17,18,19],
    15: [4, 5, 6, 10, 11, 12, 13, 14, 19, 20]
}

我需要通过以下方式将值映射到键:

{
    8: [3,4,5,6,9],
    8_11: [11,12,13,14,15],
    8_17: [17,18,19],
    15: [4,5,6],
    15_10: [10,11,12,13,14],
    15_19: [19,20]
}

代码已经尝试过:

    for k,v in new_dic.items():
            for i in range(1,len(v)):
                if(v[i]-v[i-1]>1):
                    new_dic[k]=v[:i]
                    identity_switch[str(k)+'_'+str(v[i])]=v[i:]  

标签: python

解决方案


您试图以错误的方式拆分列表。此外,您没有正确更新当前的字典。您可以尝试以下脚本。希望是comments不言自明的。

z = {
    8: [3, 4, 5, 6, 11, 12, 13, 14, 15, 17, 18, 19],
    15: [4, 5, 6, 10, 11, 12, 13, 14, 19, 20],
}

f = dict()  # Separating the cut off values which will be updated in the end
for key, value in z.items():
    value.sort()  # sorting the dictionary to get the difference properly
    l = [value[0]]
    x = value[0]
    check = True  # To check the initial cut off
    cut_off = 0  # To store initial cut off index
    for item in range(1, len(value)):
        if (value[item] - x) != 1:  # If difference is n.e 1
            if not check:  # If not first cut off updated over to be updated final dict
                f[str(key) + "_" + str(l[0])] = l
            x = value[item]
            l = [value[item]]
            if check:  # If first check store the index and turn first cut off check
                cut_off = item
                check = False
        else:
            x = value[item]
            l.append(value[item])

    if not check:  # Change the item to only accumulate diff of 1
        z[key] = value[0:cut_off]
    if l:  # If new list pending update into f
        f[str(key) + "_" + str(l[0])] = l

z.update(f)  # update original dictionary
print(z)

希望这能解决你的问题!!!


推荐阅读