Set operations for lists: pythonic hints please!

jmdeschamps at gmail.com jmdeschamps at gmail.com
Thu Oct 20 17:05:42 EDT 2005


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
?

Thanks in advance,

Jean-Marc

# My test code
# the code is not generic here
# my question only pertains to the intersection algorithm perse

from Tkinter import *
import random, sets

root=Tk()

m1 = Canvas(root,width=410,height=410)
m1.pack(fill=BOTH, expand=1)
for i in range(10):
    x=random.randrange(1,400)
    y=random.randrange(1,400)
    m1.create_oval(x,y,x+10,y+10,fill="red",tags=("etoile","rouge"))

for i in range(10):
    x=random.randrange(1,400)
    y=random.randrange(1,400)

m1.create_rectangle(x,y,x+10,y+10,fill="red",tags=("artefact","rouge"))

for i in range(10):
    x=random.randrange(1,400)
    y=random.randrange(1,400)

m1.create_rectangle(x,y,x+10,y+10,fill="green",tags=("artefact","green"))

#
i=m1.find_withtag("artefact")
j=m1.find_withtag("rouge")

s1=sets.Set(i)
s2=sets.Set(j)

s3=s1.intersection(s2)
myIntersection=tuple(s3._data.keys())

for i in myIntersection:
    m1.itemconfig(i,fill="black")

root.mainloop()




More information about the Python-list mailing list