Reputation: 67
it is a probably easy task for someone expert in python. This is my problem: I need to filter a list, saved as a json array by another list of lists containing dictionaries (they are three lists). I, thus, wrote a function having a comprehension list to get the filtered list and calling this one three times. The issue is at each iteration the list to be filtered has to be the latest got by calling my function, but what it is happening is that at each iteration my function is always passing the original list to be filtered. Therefore it isn't filtering out correctly. Problem is the first parameter (lst_to_be_filter) after the first iteration should be the result of the first filter, instead is always the original list. I will give an example of what I would like to get:
list to be filtered:
[{"k1": 1235421901, "k2": ""}, {"k1": 729291349, "k2": "Aff"}, {"k1": 741952108, "k2": "rewuie"}]
list of lists:
[[{"k1": 1235421901, "k2": ""}, {"k1": 459291349, "k2": "eijie"}],[{"k1": 1235421901, "k2": ""}, {"k1": 948521901, "k2": "vnvju"}, {"k1": 234121901, "k2": "ppp"}], [{"k1": 935591901, "k2": "sòdodo"}, {"k1": 100021901, "k2": "ju"}, {"k1": 741952108, "k2": "rewuie"}]]
final result: [{"k1": 729291349, "k2": "Aff"}]
So, after the first iteration, my fucntion removes one dictionary, in the second one nothing and in the third iteration another dictionary so that my final list has only one dictionary that I have to save as a file. Below my code:
import json
#Function creating the filtered list
def filterlist(l_all, l_admin):
l_filtered = [j for j in l_all if j not in l_admin]
with open('userstofiltered.txt', 'r+', encoding='utf-8') as r6:
json.dump(l_filtered,r6)
return l_filtered
list_filtered = list()
listofUsers = list() # list of lists of dictionaries
with open('fil1.txt', 'r', encoding='utf-8') as r1, \
open('fil2.txt', 'r', encoding='utf-8') as r2, \
open('file3.txt', 'r', encoding='utf-8') as r3, \
open('fullList.txt', 'w', encoding='utf-8') as r4, \
open('userstofiltered.txt', 'r+', encoding='utf-8') as r5:
lst_to_be_filter = json.load(r5)
print("Pre filter:Num. users", len(lst_to_be_filter))
print("users", lst_to_be_filter)
#Create list of lists named (listofUsers )
l1 = json.load(r1)
listofUsers.append(l1)
l2 = json.load(r2)
listofUsers.append(l2)
l3 = json.load(r3)
listofUsers.append(l3)
json.dump(listofUsers, r4)
for x in range(0,len(listofUsers)):
list_filtered = filterlist(lst_to_be_filter, listofUsers[x])
Upvotes: 0
Views: 51
Reputation: 12140
IIUC, you can just initialize list_filtered
right before the for
loop with lst_to_be_filter
and always pass list_filtered
to the function like so:
list_filtered = lst_to_be_filter
for x in range(0,len(liste_tipster)):
list_filtered = filterlist(list_filtered, listofUsers[x])
Then it will be updated each iteration.
Upvotes: 1