Reputation: 13
I have two lists, which are both list of lists of the same lengths
list1 [[1 3 5 7] [2 5 1 6]]
list2 [[0.5 0.3 0.7 0.1] [0.1 0.4 0.6 0.2]]
My task is: if a number in list2 is <= e.g 0.2, remove items at corresponding position from list1. So based on the above example items in list2 which are <= 0.2 are [[3] [0 3]] and the final list1 should look like this [[1 3 5] [5 1]]. The same items should then be removed from list2 so its final version would look like [[0.5 0.3 0.7] [0.4 0.6]]. The below code works well but becomes very slow if the list is long (which is the case in my model) Is the any efficient way of doing it without running loop of a loop?
let k 0
foreach list2
[
x ->
let each_element_list2 x
let each_element_list1 k list1
(foreach each_element_list2
[
i ->
if i <= 0.2
[
let rem_pos position i each_element_list2
set each_element_list2 remove-item rem_pos each_element_list2
set each_element_list1 remove-item rem_pos each_element_list1
]
]
)
set list2 replace-item k list2 each_element_list2
set list1 replace-item k list1 each_element_list1
set k k + 1
]
Thanx in advance,
Magda
Upvotes: 0
Views: 138
Reputation: 14972
This is not the most elegant code, and I don't have time to explain it step by step, but something like this should work:
to remove-items
let list1 [[1 3 5 7 ] [2 5 1 6 ]]
let list2 [[0.5 0.3 0.7 0.1] [0.1 0.4 0.6 0.2]]
if length list1 != length list2 [ error "lists should be of equal length" ]
foreach range length list1 [ i ->
let sl1 item i list1 ; extract sublist 1
let sl2 item i list2 ; extract sublist 2
let indices-to-keep (
map first ; extract the index from the pair
filter [ p -> last p > 0.2 ] ; keep the pairs where the item is <= 0.2
(map list range (length sl2) sl2) ; build a list of index/item pairs
)
let replace-sublist [ [l sl] ->
replace-item i l (map [ j -> item j sl ] indices-to-keep)
]
set list1 (runresult replace-sublist list1 sl1)
set list2 (runresult replace-sublist list2 sl2)
]
print list1
print list2
end
Just one quick note: notice that I inverted the condition (i.e., > 0.2 instead of <= 0.2), as it's easier to use a list of the indices we want to keep instead of those we want to remove.
Upvotes: 2