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

前端 未结 14 2645
孤城傲影
孤城傲影 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:41

    Since you want a random element, this will also work:

    >>> import random
    >>> s = set([1,2,3])
    >>> random.sample(s, 1)
    [2]
    

    The documentation doesn't seem to mention performance of random.sample. From a really quick empirical test with a huge list and a huge set, it seems to be constant time for a list but not for the set. Also, iteration over a set isn't random; the order is undefined but predictable:

    >>> list(set(range(10))) == range(10)
    True 
    

    If randomness is important and you need a bunch of elements in constant time (large sets), I'd use random.sample and convert to a list first:

    >>> lst = list(s) # once, O(len(s))?
    ...
    >>> e = random.sample(lst, 1)[0] # constant time
    

提交回复
热议问题