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

前端 未结 14 2567
孤城傲影
孤城傲影 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 08:04

    What I usually do for small collections is to create kind of parser/converter method like this

    def convertSetToList(setName):
    return list(setName)
    

    Then I can use the new list and access by index number

    userFields = convertSetToList(user)
    name = request.json[userFields[0]]
    

    As a list you will have all the other methods that you may need to work with

    0 讨论(0)
  • 2020-12-07 08:05

    How about s.copy().pop()? I haven't timed it, but it should work and it's simple. It works best for small sets however, as it copies the whole set.

    0 讨论(0)
提交回复
热议问题