Pergunta

Eu estou tentando fazer um código bubble sort simples para se familiarizar com lista / string manip & método de uso, mas por algum motivo, quando tento para percorrer cada valor na lista para remover espaço em branco e valores que são não ints, ele ignora alguns. Eu nem sequer chegado à parte ordenação bolha ..

#test data:  45,5j, f,e,s , , , 45,q,

    if __name__ == "__main__":
getList = input("Enter numbers separated by commas:\n").strip()
listOfBubbles = getList.split(',')
print (listOfBubbles)
i = 0
for k in listOfBubbles:
    listOfBubbles[i] = k.strip()
    print ("i = {0} -- Checking '{1}'".format(i,listOfBubbles[i]))
    if listOfBubbles[i] == '' or listOfBubbles[i] == ' ':
        del listOfBubbles[i]
        i -= 1
    else:
        try:
            listOfBubbles[i] = int(listOfBubbles[i])
        except ValueError as ex:
            #print ("{0}\nCan only use real numbers, deleting '{1}'".format(ex, listOfBubbles[i]))
            print ("deleting '{0}', i -= 1".format(listOfBubbles[i]))
            del listOfBubbles[i]
            i -= 1
        else:
            print ("{0} is okay!".format(listOfBubbles[i]))
    i += 1

print(repr(listOfBubbles))

Output:

    Enter numbers separated by commas:
45,5j, f,e,s , , , 45,q,
['45', '5j', ' f', 'e', 's ', ' ', ' ', ' 45', 'q', '']
i = 0 -- Checking '45'
45 is okay!
i = 1 -- Checking '5j'
deleting '5j', i -= 1
i = 1 -- Checking 'e'
deleting 'e', i -= 1
i = 1 -- Checking ''
i = 1 -- Checking '45'
45 is okay!
i = 2 -- Checking 'q'
deleting 'q', i -= 1
[45, 45, ' ', ' 45', 'q', '']
Foi útil?

Solução

Como sobre uma maneira mais Python?

#input
listOfBubbles = ['45', '5j', ' f', 'e', 's ', ' ', ' ', ' 45', 'q', '']
#Copy input, strip leading / trailing spaces. Remove empty items
stripped = [x.strip() for x in listOfBubbles if x.strip()]    

# list(filtered) is ['45', '5j', 'f', 'e', 's', '45', 'q']
out = []
for val in filtered:
  try:
    out.append(int(val))
  except:
    # don't do anything here, but need pass because python expects at least one line
    pass 
# out is [45, 45]

Finalmente, para saltar para a sua resposta correta

out.sort()

Atualização Para esclarecer passagem

>>> for i in range(0,5):
        pass
        print i

0
1
2
3
4

Outras dicas

Nunca alterar a própria lista que você está looping on - dentro do for k in listOfBubbles: loop, você está excluindo alguns itens de que muito lista, e que perturba a lógica looping interno. Existem muitas abordagens alternativas, mas a correção mais simples é fazer um loop em um cópia da lista que pretende alterar: for k in list(listOfBubbles):. Pode haver mais problemas, mas este é o primeiro.

Não importa, fixa-lo. I alterar o loop de um para .. para um tempo ..

if __name__ == "__main__":
    getList = input("Enter numbers separated by commas:\n").strip()
    listOfBubbles = getList.split(',')
    print (listOfBubbles)
    i = 0
    while i < len(listOfBubbles):
        listOfBubbles[i] = listOfBubbles[i].strip()
        print ("i = {0} -- Checking '{1}'".format(i,listOfBubbles[i]))
        if listOfBubbles[i] == '' or listOfBubbles[i] == ' ':
            del listOfBubbles[i]
            i -= 1
        else:
            try:
                listOfBubbles[i] = int(listOfBubbles[i])
            except ValueError as ex:
                #print ("{0}\nCan only use real numbers, deleting '{1}'".format(ex, listOfBubbles[i]))
                print ("deleting '{0}', i -= 1".format(listOfBubbles[i]))
                del listOfBubbles[i]
                i -= 1
            else:
                print ("{0} is okay!".format(listOfBubbles[i]))
        i += 1

    print(repr(listOfBubbles))

Você não pode usar um iterador para excluir de uma lista, porque a variação do comprimento.

Em vez disso você deve usar um índice no loop for (ou um tempo loop).

Depois de ter removido um item que você precisa para percorrer a lista novamente.

pseudo-código:

again:
for i = 0 to list.count - 1
{
  if condition then 
    delete list[i] 
    goto again;
}

Se você estiver indo para apagar a partir de uma lista enquanto interagindo através dele, percorrer a lista em ordem inversa:

for( i = myList.length - 1; i >= 0; i-- ) {
   // do something
   if( some_condition ) {
      myList.deleteItem( i );
   }
}

Desta forma, você não vai pular nenhum item na lista como encurtar a lista não afeta nenhum iterações futuras. Claro, o trecho acima assume que o método DeleteItem é suportado na lista de classe / série e faz as coisas apropriadas.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top