Getting some element from sets.Set

John Machin sjmachin at lexicon.net
Fri May 4 18:06:57 EDT 2007


On May 4, 6:23 pm, "jm.sur... at no.spam.gmail.com" <jm.sur... at gmail.com>
wrote:
> On May 4, 11:34 am, Peter Otten <__pete... at web.de> wrote:
>
>
>
> > jm.sur... at no.spam.gmail.com wrote:
> > > It is not possible to index set objects. That is OK.
> > > But, what if I want to find some element from the Set.
>
> > > from sets import Set
> > > s = Set( range(12 )
>
> > > if I do pop, that particular element gets removed.
> > > I do not want to remove the element, but get some element
> > >  from the Set.
>
> > > s.some_element() # Is not available
>
> > > Is there a way to do this. I am doing it like this:
>
> > > for x in s: break
>
> > > Now x is /some_element/ from s.
>
> > A set is probably not the appropriate container then. What is your use case?
>
> > Peter
>
> Peter, I need to do a lot of union and intersection operations on
> these elements. So, set is a must for me in this case.

Errmm, union and intersection operations each apply to two (or more)
sets, not to the elements of a set.

>
> In the particular case, I have to read an attribute from any one of
> the elements, which one doesn't matter because this attribute value is
> same across all elements in the set.
>

Well, I'm not so easily convinced as some people :-)

You say the rule is that each element in a set has
element.someattribute == somevalue.

You have n sets set0, set1, ....

Let u be the number of unique somevalues (1 <= u <= n)

If u > 1, then after setn = union(set0, set1), setn may not conform to
the rule -- does this matter?

You have a rather redundant data structure, and perhaps should
consider refactoring it.

A physical analogy: somebody has packed fruit into boxes, all the
bananas in one box, the oranges in a second box, the apples in a third
box, etc, without writing labels on the boxes. The somebody has
however laboriously pasted a label ("banana", "orange", etc) on each
piece of fruit. You now need to grab an object from each box,
presumably to identify the box contents. How close is this analogy to
your scenario?

Cheers,
John




More information about the Python-list mailing list