I would like to loop a list and remove element if it meets the requirement. At the same time, I would transform the removed element and add the transformation result to another list.
Right now, I have implemented above logic by following code:
delete_set = set([])
for item in my_list:
if meet_requirement(item):
another_list.append = transform(item)
delete_set.add(item)
my_list = filter(lambda x:x not in delete_set, my_list)
The code is not so straight-forward, is there a better way to implement the logic?
You could do this with comprehensions only.
delete_set = set(I for I in my_list if meet_requirement(I))
another_list.extend(transform(I) for I in delete_set)
# or extend(transform(I) for I in my_list if I in delete_set), if duplicates/order matter
my_list = [I for I in my_list if I not in delete_set]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With