猿问

从python中的字典创建子字典

函数 criarB 返回:


{269476: 200129, 209624: 200129 ...}

 200129 position in aux2, '200129 and 209624 are keys'

如何根据键拆分dict,如果keys % 10 = 0 必须存储在list[0]中


list = [[], [], ...]

类完成:


class Buckets:


def __init__(self, keys, palavras, tamanhoP):

    self.listaBuckts = dict()

    self.listaHash = list()

    self.keys = list(keys)


    aux = list(zip(keys, palavras))

    self.aux2 = list()


    for i in range(0, len(aux), tamanhoP):

        self.aux2.append(dict(aux[i:i + tamanhoP]))


def criarB(self):

    for i, pag in enumerate(self.aux2):

        for v in pag.keys():

            self.listaBuckts[v] = i

    return self.listaBuckts


def indexar(self):

    count = 0

    buckets = [[] for _ in range(10)]


    for r in range(0, len(buckets)):

        for s in range(0, len(self.listaBuckts)):

            if s % 3 == 0:

                buckets[r].append([v + count for v in self.listaHash[s:s + 3]])

        count += 1

    return buckets[0]

“索引”功能使用一个只包含索引的列表,如何使用 self.buckets 字典的键并根据功能划分字典


试图:


class Buckets:


def __init__(self, keys, palavras, tamanhoP):

    self.listaBuckts = dict()

    self.listaHash = list()

    self.keys = list(keys)


    aux = list(zip(keys, palavras))

    self.aux2 = list()


    for i in range(0, len(aux), tamanhoP):

        self.aux2.append(dict(aux[i:i + tamanhoP]))


def criarB(self):

    for i, pag in enumerate(self.aux2):

        for v in pag.keys():

            self.listaBuckts[v] = i

    return self.listaBuckts


def indexar(self):

    test = [[] for _ in range(10)]


    for x in self.listaBuckts:

        i = x % 10

        test[i].append([x, dict[x]])

    return test[0]


烙印99
浏览 139回答 2
2回答

GCT1015

您可以使用列表理解:listOfDicts = [{k:v for k,v in dictionary.items() if k%10==i} for i in range(10)]或循环:listOfDicts = [ dict() for _ in range(10) ]for key,value in dictionary.items():    listOfDicts[key%10].update({key:value})

繁华开满天机

如果要根据键将字典拆分为两个列表。我认为以下可以工作dict #The dictionary returned from function crairBa = [] #List to save keys and values for key%10==0b = [] #List for key%10!=0for x in dict:    if x%10==0:        a.append([x,dict[x]]) #Here I have saved both keys and values in the list, you can edit according to your need.    else:        b.append([x,dict[x]])编辑:如果您必须将数据拆分为行等于键 % 10 的二维列表,那么我认为以下方法可以工作。list = [[] for _ in range(10)]for x in dict:    i = x%10    list[i].append([x,dict[x]])
随时随地看视频慕课网APP

相关分类

Python
我要回答