1

Possuo a seguinte função em python

def playersID(self, listDetals):
        listPlayersID = []
        tempDict = {}
        for x in listDetals:
            for y in x['result']['players']:
                tempDict.clear()
                tempDict['match_id'] = x['result']['match_id']
                tempDict.update(y)
                listPlayersID.append(tempDict)
        return listPlayersID

O parametro "listDetals" é uma lista de Dict e o retorno da função tambem é uma lista de Dicionario com um pedaço de listDetals em cada posição. O problema esta no comando "append".

Toda vez que ele é chamado, ele preenche TODA a lista novamente, em vez de apenas criar uma nova posição ao final dela. Alguem tem ideia do por quê disso?

1
  • Tente trocar tempDict.clear() para tempDict = {} e veja se funciona.
    – Paulo
    5/09/2015 às 1:34

1 Resposta 1

1

Quando você usa tempDict.clear() ele afeta a variável que também já foi colocada na lista, basta alterar para tempDict = {}.

def playersID(self, listDetals):
    listPlayersID = []
    for x in listDetals:
        for y in x['result']['players']:
            tempDict = {'match_id': x['result']['match_id']}        
            tempDict.update(y)
            listPlayersID.append(tempDict)
    return listPlayersID

Detalhe, append() vai adicionar sempre ao final da lista, nunca vai substituir toda a lista pelo novo elemento. Reveja seu código, de preferência use unittest.

1
  • 1
    Muito obrigado! Troquei o tempDict.clear() para tempDict = {} e resolveu!
    – Terry
    5/09/2015 às 1:55

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .