python - 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:]
解决方案
您试图以错误的方式拆分列表。此外,您没有正确更新当前的字典。您可以尝试以下脚本。希望是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)
希望这能解决你的问题!!!
推荐阅读
- laravel - Laravel artisan cron 任务无法在 ubuntu 18.10 上运行
- java - 如何将 \timing 值插入到表中?
- android - 尝试检查数组条目时不断收到“IndexOutOfBoundsException:Index:0,Size:0”
- autohotkey - AHK:从列表中删除重复项,并将重复计数添加到各个列表项
- java - 如何获取蓝牙配对设备的设备名称?
- node.js - 从存储在 Google Cloud Storage 中的 gzipped csv 文件中读取,而无需先下载文件
- asp.net - 用于进行汇总的动态 linq 查询,例如 sum 和 average
- continuous-integration - 将 Travis Ci 与 GitHub Pages 错误一起使用:gh-token 无效
- opencart - 如何在类别页面 Opencart 3 上显示带有图像的子类别
- arduino - arduino 无法打开树莓派的红外线传感器