Shortest way to find if a string matchs an object's attribute value in a list of objects of that type in Python
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 nam开发者_StackOverflow社区es. 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.
any(obj for obj in objs if obj.name==name)
Note, that it will stop looping after first match found.
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.
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]
if string in [x.name for x in list_of_x]
for i in listOfItemsOfTypeX:
if i.name == myString: return True
return False
精彩评论