matching objects by a tuple field criterion

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Jun 10 07:37:23 EDT 2007


On Sun, 10 Jun 2007 03:58:44 -0700, bullockbefriending bard wrote:

> i have a large collection of python objects, each of which contains an
> integer 6-tuple as part of its data payload. what i need to be able to
> do is select only those objects which meet a simple tuple element
> wildcard matching criterion. e.g. given the following python objects:
> 
>     object A includes tuple (1,2,3,4,5,6)
>     object B includes tuple (1,4,4,4,11,1)
>     object C includes tuple (1,3,9,1,1,1)
> 
> all tuples are unique. for what it's worth, the values in each field
> are independent of the other fields and range from 1 to 14. although
> 'large', my collection is sparse cf. the 14^6 possible tuples.
> 
> i want to search on *one only* tuple field/value. if my search
> criterion is (*,*,*,4,*,*), then i want to find object A and object B.
> if (1,*,*,*,*,*), i want to find objects A, B, and C, etc. i will only
> ever specify an integer match for one tuple field.
> 
> i can think of some naive approaches, but is there an elegant way to
> do this?

Instead of passing a wild-card tuple like (*,*,*,4,*,*) simply pass the
integer you want to match and the position you want to match it in.

As a generator:


def matcher(list_of_objects, what, where):
    for obj in list_of_objects:
        if obj.data[where] == what:
            yield obj


As a generator expression:

(obj for obj in list_of_objects if obj.data[what] == where)



-- 
Steven.




More information about the Python-list mailing list