访问集合的唯一元素 [英] Access the sole element of a set

查看:68
本文介绍了访问集合的唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个 set,我正在根据条件从中删除元素.当集合只剩下 1 个元素时,我需要返回该元素.我如何从集合中访问这个元素?

一个简化的例子:

S = set(range(5))对于范围内的 i (4):S = S - {i}# 现在 S 只有 1 个元素:4返回 ?# 我应该如何访问这个元素# 一个蹩脚的方法如下# 对于 S 中的 e:# 返回 S

解决方案

使用 set.pop:

<预><代码>>>>{1}.pop()1>>>

在您的情况下,它将是:

返回 S.pop()

<小时>

但是请注意,这将从集合中删除该项目.如果这是不可取的,您可以使用 min|max:

return min(S) # 'max' 也可以在这里工作

演示:

<预><代码>>>>S = {1}>>>分钟)1>>>秒设置([1])>>>最大值(S)1>>>秒设置([1])>>>

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

解决方案

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

这篇关于访问集合的唯一元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆