Skip to main content
 首页 » 编程设计

python之获取长度(/基数)为 1 的集合项而不删除它的首选 Python 方法

2025年05月04日24EasonJim

给定集合 s,下面哪个片段看起来更好?

if len(s) == 1: 
    v = s.copy().pop() 
    # important stuff using variable v takes place here 

或

if len(s) == 1: 
    v = s.pop() 
    s.add(v) 
    # important stuff using variable v takes place here 

或

if len(s) == 1: 
    for v in s: 
        # important stuff using variable v takes place here 

我想最后一段是最有效的,但是使用一个实际上从不循环的循环看起来不是很傻吗?

为什么 python sets 没有替代弹出方法而不删除项目?

这似乎是一个微不足道的问题,但是当我多次遇到这种情况时,它就成了一个需要挠痒痒的问题!

请您参考如下方法:

Why don't python sets have an alternative method to pop that doesn't remove the item?

如果您想在不更改集合结构的情况下访问第一个(也是唯一一个)项目,请使用迭代器:

v = iter(s).next() 

这在 Python 3 之前有效。在 Python 3 中,您需要使用内置的 next 函数:

v = next(iter(s))