The following code 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 we need to know if elements of alguns
are already known, because they are in the todos
vector. The already known elements, which are in the todos
vector, are removed from the 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 that 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
was not removed, perhaps because it was repeated, even though it is in todos
. If you modify the code to loop through the alguns
vector and check that the element is in todos
, and then remove it, it also does not work:
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)
Output:
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 on what I can do to resolve? I thought about ordering the vectors, but I do not think it's an option, because of the type of element I'm using in the vectors of the original code.
Thanks for any help.