Set operations for lists: pythonic hints please!

Diez B. Roggisch deets at nospam.web.de
Thu Oct 20 18:03:26 EDT 2005


jmdeschamps at gmail.com wrote:
> Working with several thousand tagged items on a Tkinter Canvas, I want
> to change different configurations of objects having a certain group of
> tags.
> 
> I've used the sets module, on the tuple returned by Tkinter.Canvas.
> find_withtag() method.
> 
> Since this method takes only one tag at time, I use it for each tag
> that is part of the look-up group, create a set object for each tuple
> and intersect the resulting sets, that I tuple out again to feed a loop
> to change the configuration of the items.
> 
> Anyone have a more pythonic way (or better performing ) way to suggest
> ?

It depends. If the search on tags is implemented linear, it might be 
better to loop over all items and filter suing a compound predicate, 
like this:

rouge_artefacts = [item for m1.all_itmes() if item.has_tag("rouge") and 
item.has_tag("artefact")]

Please note that I don't know TKinter's API, but I can't imagine that it 
lacks the possibility to fettch a list of all items and query an item 
for it tags. The synopsis may vary from above, thogh.

But if tkinter stores the tagged items as mapping of tag -> set/list, 
then I think your approach is as fast as you can get. Time it out. And 
maybe another thing would be to manage that tagging relation yourself.

Regards,

Diez



More information about the Python-list mailing list