0
The code below is a demonstration of what I’m trying to do: I have a vector (todos) in which elements are added. The second vector (alguns) also receives new elements, and I need to know if the elements of alguns are already known to be in the vector todos. The already known elements, which are in the vector todos, are removed from the vector alguns:
todos = ["b", "g", "c", "e", "d", "a", "h", "d"]
print("todos:", todos)
alguns = ["h", "c", "k", "a", "d", "j", "a"]
print("alguns:", alguns)
for letra in todos:
if letra in alguns:
print("remover letra:", letra, ", pois esta em alguns:", alguns)
alguns.remove(letra)
print ("alguns apos limpeza:", alguns)
The output of the execution, in the form the code is, is as follows:
todos: ['b', 'g', 'c', 'e', 'd', 'a', 'h', 'd']
alguns: ['h', 'c', 'k', 'a', 'd', 'j', 'a']
remover letra: c , pois esta em alguns: ['h', 'c', 'k', 'a', 'd', 'j', 'a']
remover letra: d , pois esta em alguns: ['h', 'k', 'a', 'd', 'j', 'a']
remover letra: a , pois esta em alguns: ['h', 'k', 'a', 'j', 'a']
remover letra: h , pois esta em alguns: ['h', 'k', 'j', 'a']
alguns apos limpeza: ['k', 'j', 'a']
Note that the last element of alguns has not been removed, perhaps because it is repeated, despite being in todos. If you modify the code to go through the vector alguns and check that the element is in todos, and then take it out, it doesn’t work either:
todos = ["b", "g", "c", "e", "d", "a", "h", "d"]
print("todos:", todos)
alguns = ["h", "c", "k", "a", "d", "j", "a"]
print("alguns:", alguns)
for letra in alguns:
if letra in todos:
print("remover letra:", letra, ", pois esta em alguns:", alguns)
alguns.remove(letra)
print ("alguns apos limpeza:", alguns)
Exit:
todos: ['b', 'g', 'c', 'e', 'd', 'a', 'h', 'd']
alguns: ['h', 'c', 'k', 'a', 'd', 'j', 'a']
remover letra: h , pois esta em alguns: ['h', 'c', 'k', 'a', 'd', 'j', 'a']
remover letra: a , pois esta em alguns: ['c', 'k', 'a', 'd', 'j', 'a']
remover letra: a , pois esta em alguns: ['c', 'k', 'd', 'j', 'a']
alguns apos limpeza: ['c', 'k', 'd', 'j']
Any suggestions what I can do about it? I thought about sorting the vectors, but I think it’s not an option, by the type of element I’m using in the vectors of the original code.
I appreciate any help.
consider the possibility of using sets
set(), will work better for what you want to do– nosklo
I will search. Thank you!
– Daniel Elias