Python - testing if an object attribute is equal to a given value

Say you have a list of people.

class Person:
    def __init___(self, name, id): = name = id

people = []
for x in xrange(0,100)
    #find people and append to people list

Now, I have a list of people objects. How could I most efficiently find, say, a person whose name is "Bob" from the people list?


With just a list and no other indices, you have to use a list comprehension:

matching = [p for p in people if == 'Bob']

but if you have to do that a lot, you may want to create an index:

from collections import defaultdict

nameindex = defaultdict(list)
for person in people:
    nameindex[] = person

nameindex['bob']  # a list of people named Bob.

This way you only have to loop through all your people once (cost O(N)), after which any name lookup has constant cost (O(1)).

Need Your Help

Python - Delete comments in a Python code

python comments

So i have to write a code that will delete every # comment in a Python code...

Different layouts and i18n in JSP application

java model-view-controller jsp tomcat

I have a bunch of JSP files and backend in Tomcat. I have 3 different versions of JSP with same logic inside but with different layouts. So if I change some logic I have three JSP file to fix.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.