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.
views:
112answers:
5
+5
A:
any(obj for obj in objs if obj.name==name)
Note, that it will stop looping after first match found.
Denis Otkidach
2009-12-28 13:40:01
+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
2009-12-28 13:43:04
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
2009-12-28 14:30:14
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
2009-12-28 15:28:21
+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
2009-12-28 13:45:13
A:
for i in listOfItemsOfTypeX:
if i.name == myString: return True
return False
inspectorG4dget
2009-12-28 13:45:37