I want to make a function for while loop in the example below with the changing in if-statement of global variables (fil_...) and local variable in while loop (rs_list[i]) but I can't get the result as expecting.
I have a result list like that: rs_list = [1, 2, 1, 3, 2, 4, 'a', 'b', 'a', 'c', 'd', 'b', 'a']
the rs_list
will be filtered based on the conditions changing in steps:
Step01: code doing sth
fil_list_01 = [1, 2, 4, 'a', 'b', 'd']
# Use while loop to filter rs_list
i = 0
while i < len(rs_list):
prd = rs_list[i]
if prd not in fil_list_01:
rs_list.pop(i)
else:
i = i + 1
Step02: code doing sth
fil_list_02 = [1, 2, 4]
# Use while loop to filter numbers in rs_list
i = 0
while i < len(rs_list):
prd = rs_list[i]
if prd not in fil_list_02:
rs_list.pop(i)
else:
i = i + 1
Step03: code doing sth
fil_03 = 1.5
# Use while loop to filter numbers > fil_03 in rs_list
i = 0
while i < len(rs_list):
prd = rs_list[i]
if prd < fil_03:
rs_list.pop(i)
else:
i = i + 1
rs_list --> [2, 4]
So I create a function for while loop like that:
def filter_while_loop(input_list, input_condition):
i = 0
output_list = input_list
while i < len(input_list):
prd = input_list[i]
if exec(input_condition):
output_list.pop(i)
else:
i = i + 1
return output_list
Then using it in the code above like that:
Step01: code doing sth
fil_list_01 = [1, 2, 4, 'a', 'b', 'd']
# Use function to filter rs_list
rs_list = filter_while_loop(rs_list, "prd not in fil_list_01")
rs_list --> [1, 2, 1, 3, 2, 4, 'a', 'b', 'a', 'c', 'd', 'b', 'a']
But there are not any effect on the rs_list. How could I use a function for filtering while loop in this example with the changing in if-statement with global variable (eg: fil_list_01
) and local variable in while loop (prd = input_list[i]
)?
Aucun commentaire:
Enregistrer un commentaire