1

We have some objects with properties

class my_object: def __init__(self, type, name): self.type = type self.name = name 

And a list which contains many object with different type and name values.

What I need is a comprehension which does something like:

if my_object.type == 'type 1' in object_list: object_list.remove(all objects with name == 'some_name') 

4 Answers 4

2

I think what you need is :

if any(obj.type == 'type 1' for obj in object_list): object_list = [obj for obj in object_list if obj.name != 'some_name'] 
Sign up to request clarification or add additional context in comments.

4 Comments

not efficient ... get rid of the if ... you are looping through twice for no reason
@JoranBeasley -- What do you mean? The looping really isn't all that costly and to factor the other test into the list-comp would change the logic (although maybe only slightly).
ahh yeah your right .. i guess it does ... I just read the problem statement wrong
@Mike Graham: But the OP said that it does. Why are you not clear?
2

I think you are looking for:

object_list = filter(lambda x: x.name != 'some_name', object_list) 

3 Comments

Yeah, I think so too... Although, I'd advise the list-comp here.
meh ... why? I know filter isnt more efficient with lambdas ... but to me what you are doing is "filtering" the list, and so using filter is more natural to me ...
@JoranBeasley -- I suppose it's because every time you see a lambda, you have to figure out what it's doing. I think most people prefer not to look at them if possible arguing that the syntax for the list-comprehension is more elegant and easier to read.
0
if hasattr(my_object,"some_attribute") : doSomething() 

although in your case I think you want

filter(lambda x:not hasattr(x,"name") or x.name != "some_name",my_list_of_objects) 

Comments

0

You could do:

def remove_objects(obj_list,*args,**kwargs): for n_count,node in enumerate(obj_list[::]): del_node=False for k,v in kwargs.items(): if hasattr(node,str(k)): if getattr(node,str(k))==v: del_node=True break if del_node: del obj_list[n_count] 

And use it like:

class HelloWorld(object): lol="haha" my_list_of_objects=[HelloWorld for x in range(10)] remove_objects(my_list_of_objects,lol="haha") 

2 Comments

dont modify a list as you are iterating over it! especially when going from low to high, but really even when going high to low.
Wow... That looks ... Complicated. Also, I'm hesitant to say that I believe this works because you're deleting objects from the list as you iterate over it. Finally, rather than keeping a counter yourself, you could use the builtin enumerate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.