Access the sole element of a set

前端 未结 6 701
Happy的楠姐
Happy的楠姐 2020-12-01 23:13

I have a set in Python from which I am removing elements one by one based on a condition. When the set is left with just 1 element, I need to return that elemen

6条回答
  •  悲&欢浪女
    2020-12-01 23:46

    Use set.pop:

    >>> {1}.pop()
    1
    >>>
    

    In your case, it would be:

    return S.pop()
    

    Note however that this will remove the item from the set. If this is undesirable, you can use min|max:

    return min(S) # 'max' would also work here
    

    Demo:

    >>> S = {1}
    >>> min(S)
    1
    >>> S
    set([1])
    >>> max(S)
    1
    >>> S
    set([1])
    >>> 
    

提交回复
热议问题