如何将子列表分解成字典? [英] How to break sub lists into a dict?
问题描述
伙计们,我创建了一个字典,并使用以下功能对其进行了划分:
Well guys, I created a dict, and divided it using the function:
listOfDicts = [{k:v for k,v in dictionary.items() if k%10==i} for i in range(10)]
由此,我得到了10个子列表:
From that, I got 10 sublists:
listOfDicts[0 a 9]
listOfDict[0]: {0: 0, 10: 5, 20: 10, 30: 15, 40: 20, 50: 25, 60: 30, 70: 35, 80: 40, 90: 45}
但是,如果我想将子列表分成相等的大小(在大小= 3的情况下)并添加单个字典,该怎么办?
But what if I want to divide the sublists into equal sizes (in the case size = 3) and add in a single dict:
listOfDict[0]: {{0: 0, 10: 5, 20: 10}, {30: 15, 40: 20, 50: 25}, {60: 30, 70: 35, 80: 40}, {90: 45}}
推荐答案
根据您要查找的内容,有几种选择:
There are several alternatives depending on what you are looking for:
dictionary = {0: 123, 10: 345, 20: 678, 30: 123, 40: 345, 50: 678, 60: 123, 70: 345, 80: 678 ,90: 123 }
1)列表中固定数量的插槽(即始终为10):
1) Fixed number of slots in list (i.e. always 10):
slotCount = len(dictionary)//10
items = sorted(dictionary.items())
listOfDict = [ dict(items[i:i+ slotCount])
for i in range(0,len(items),slotCount) ]
listOfDict += [ {} for _ in range(slotCount,len(items),-1) ]
2)每个插槽的固定条目数(可变插槽数):
2) Fixed number of entries per slots (variable number of slots):
bucketSize = 10
items = sorted(dictionary.items())
listOfDict = [ dict(items[i:i+bucketSize])
for i in range(0,len(items),bucketSize) ]
3)条目和插槽的平衡数量:
3) Balanced number of entries and slots:
bucketSize = int(len(dictionary)**0.5)
items = sorted(dictionary.items())
listOfDict = [ dict(items[i:i+bucketSize])
for i in range(0,len(items),bucketSize) ]
4)在列表中的10个插槽上均匀分布数据:
4) Evenly distributed data over the 10 slots in the list:
slotCount = 10
listOfDicts = [ {k:v for k,v in dictionary.items()
if abs(hash(str(k))) % slotCount == i}
for i in range(slotCount) ]
注意:所有这些方法将允许在创建列表之后确定键属于哪个插槽的方法.前三种方法按键的排序顺序分解字典,因此可以使用二等分搜索算法.第四个仅使用哈希函数,该函数直接返回密钥的插槽号
这篇关于如何将子列表分解成字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!