Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - Access the sole element of a set

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 element. How do I access this element from the set?

A simplified example:

S = set(range(5))
for i in range(4):
    S = S - {i}
# now S has only 1 element: 4
return ? # how should I access this element
# a lame way is the following
# for e in S:
#    return S
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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])
>>> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...