Access the sole element of a set

2019-01-09 14:48发布

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

标签: python set
4条回答
姐就是有狂的资本
2楼-- · 2019-01-09 14:53

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])
>>> 
查看更多
甜甜的少女心
3楼-- · 2019-01-09 14:55

Sorry, late to the party. To access an element from a set you can always cast the set into a list and then you can use indexing to return the value you want.

In the case of your example:

return list(S)[0]
查看更多
Luminary・发光体
4楼-- · 2019-01-09 14:58

You can assign the last element to a variable, using star operation.

>>> a={"fatih"}
>>> b=str(*a)
>>> b
'fatih'

Now the varible b have a string object.

If the sole elemant is a number, you could use int():

>>> a={1}
>>> c=int(*a)
>>> c
1
查看更多
神经病院院长
5楼-- · 2019-01-09 15:10

I would use:

e = next(iter(S))

This is non-destructive and works even when there is more than one element in the set. Even better, it has an option to supply a default value e = next(iter(S), default).

You could also use unpacking:

[e] = S

The unpacking technique is likely to be the fastest way and it includes error checking to make sure the set has only one member. The downside is that it looks weird.

查看更多
登录 后发表回答