Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be the pythonic way to implement following logic?

Tags:

python

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?

like image 575
xiao 啸 Avatar asked Jun 07 '11 13:06

xiao 啸


1 Answers

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]
like image 98
Cat Plus Plus Avatar answered Sep 30 '22 09:09

Cat Plus Plus