views:

112

answers:

5

I have a list with objects of x type. Those objects have an attribute name. I want to find if a string matchs any of those object names. If I would have a list with the object names I just would do if string in list, so I was wondering given the current situation if there is a way to do it without having to loop over the list.

+1  A: 

if string in [x.name for x in list_of_x]

ahatchkins
+5  A: 
any(obj for obj in objs if obj.name==name)

Note, that it will stop looping after first match found.

Denis Otkidach
+4  A: 

Here's another

dict( (o.name,o) for o in obj_list )[name]

The trick, though, is avoid creating a list obj_list in the first place.

Since you know that you're going to fetch objects by the string value of an attribute, do not use a list, use a dictionary instead of a list.

A dictionary can be trivially "searched" for matching strings. It's a better choice than a list.

S.Lott
it works if he would have the name attribute as a key, but when multiple objects have same name it only gives the last in array..but good one.. +1
Ahmad Dwaik
Thanks for the clarification Ahmad Dwaik. I didnt mention it in my question, but the object names are unique, meaning S.Lott answer is my case
Pablo
+4  A: 

What do you want to do if the string matches? Do you just want to return True/False, or return a list of objects that match? To return a boolean:

any(obj.name == name for obj in objs)

(I find this slightly more readable than Denis Otkidach's version).

to filter the list:

[obj for obj in objs if obj.name == name]
Dave Kirby
I want to return true or false. it's to stop an infinite recursion
Pablo
A: 
for i in listOfItemsOfTypeX:
    if i.name == myString: return True
return False
inspectorG4dget