How to retrieve an element from a set without removing it?

前端 未结 14 2615
孤城傲影
孤城傲影 2020-12-07 07:17

Suppose the following:

>>> s = set([1, 2, 3])

How do I get a value (any value) out of s without doing s.pop()

14条回答
  •  执念已碎
    2020-12-07 07:48

    To provide some timing figures behind the different approaches, consider the following code. The get() is my custom addition to Python's setobject.c, being just a pop() without removing the element.

    from timeit import *
    
    stats = ["for i in xrange(1000): iter(s).next()   ",
             "for i in xrange(1000): \n\tfor x in s: \n\t\tbreak",
             "for i in xrange(1000): s.add(s.pop())   ",
             "for i in xrange(1000): s.get()          "]
    
    for stat in stats:
        t = Timer(stat, setup="s=set(range(100))")
        try:
            print "Time for %s:\t %f"%(stat, t.timeit(number=1000))
        except:
            t.print_exc()
    

    The output is:

    $ ./test_get.py
    Time for for i in xrange(1000): iter(s).next()   :       0.433080
    Time for for i in xrange(1000):
            for x in s:
                    break:   0.148695
    Time for for i in xrange(1000): s.add(s.pop())   :       0.317418
    Time for for i in xrange(1000): s.get()          :       0.146673
    

    This means that the for/break solution is the fastest (sometimes faster than the custom get() solution).

提交回复
热议问题