Reputation: 117
Be the following list of elements:
listELEMENTS = ['aaa', 'bbb', 'ccc']
and be the following txt file (elements.txt) with lists of elements that should be kept in the list:
elements.txt
aaa
ccc
ddd
the idea is to remove the elements from the listELEMENTS that are not in the elements elements.txt file, so the final result after deletion will be this:
listELEMENTS = ['aaa', 'ccc']
the code I made was this, but it is eliminating all elements. Does anyone know where the error is?
with open("elements.txt") as f:
for line in f:
(key) = line.split()
for i in listELEMENTS :
if i not in key:
listELEMENTS.remove(i)
Upvotes: 0
Views: 824
Reputation: 336
You're doing two iterations on your code, one for each line in the file and inside that you're doing one for each element in the list, so, getting your example we would have:
list_elements = ['aaa', 'bbb', 'ccc']
line = 'aaa'
key = ['aaa']
Inside this iteration another one is going to happen, so:
- Iteration 01:
i = 'aaa'
i is in key, no element removed.
- Iteration 02:
i = 'bbb'
i is NOT in key, 'bbb' gets removed.
Finished iteration because an element was removed from the list
list_elements = ['aaa', 'ccc']
line = 'ccc'
key = ['ccc']
Inside this iteration another one is going to happen, so:
- Iteration 01:
i = 'aaa'
i is NOT in key, 'aaa' gets removed INCORRECTLY.
Iterator finished.
I suggest you to change the way you're removing the data from your list, instead of editing a list you're iterating over it, create a new one with the data that you're actually going to be using:
listELEMENTS = ['aaa', 'bbb', 'ccc']
used_elements = []
with open("elements.txt") as f:
file_content = f.read().splitlines()
for i in listELEMENTS:
if i in file_content:
used_elements.append(i)
print(used_elements)
Upvotes: 1
Reputation: 9504
The problem in your code is that you are checking for each element of listELEMENTS
if it exists in a specific element of the file instead of all file's elements (if i not in key
).
Change your code to:
listELEMENTS = ['aaa', 'bbb', 'ccc']
with open("elements.txt") as f:
file_elements = f.read().splitlines() # read all elements of the file into a list
for i in listELEMENTS:
if i not in file_elements:
# check that i not exists in the full list of elements
listELEMENTS.remove(i)
print(listELEMENTS) # ['aaa', 'ccc']
Or, you can do it in a bit shorter way using list comprehension:
with open("elements.txt") as f:
file_elements = f.read().splitlines()
listELEMENTS = [i for i in listELEMENTS if i in file_elements]
print(listELEMENTS) # ['aaa', 'ccc']
Upvotes: 1
Reputation: 615
hi you can use intersection
:
a = ['aaa', 'bbb', 'ccc']
b = ['aaa', 'ccc', 'ddd']
list(set(a).intersection(b))
['ccc', 'aaa']
so you can do something like that:
listELEMENTS = ['aaa', 'bbb', 'ccc']
with open("elements.txt") as f:
file_elements = f.read().splitlines()
#print(file_elements)
listELEMENTS =list(set(listELEMENTS).intersection(file_elements))
print(listELEMENTS)
['ccc', 'aaa']
Upvotes: 1