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

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

    Another option is to use a dictionary with values you don't care about. E.g.,

    
    poor_man_set = {}
    poor_man_set[1] = None
    poor_man_set[2] = None
    poor_man_set[3] = None
    ...
    

    You can treat the keys as a set except that they're just an array:

    
    keys = poor_man_set.keys()
    print "Some key = %s" % keys[0]
    

    A side effect of this choice is that your code will be backwards compatible with older, pre-set versions of Python. It's maybe not the best answer but it's another option.

    Edit: You can even do something like this to hide the fact that you used a dict instead of an array or set:

    
    poor_man_set = {}
    poor_man_set[1] = None
    poor_man_set[2] = None
    poor_man_set[3] = None
    poor_man_set = poor_man_set.keys()
    

提交回复
热议问题