1

给定 set 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 集没有替代方法来弹出不删除项目?

这似乎是一个微不足道的问题,但是当我多次遇到这种情况时,它已经变得需要抓挠了!

4

2 回答 2

5

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

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

v = iter(s).next()

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

v = next(iter(s))
于 2011-05-23T01:17:44.363 回答
3

您可以将唯一的元素分配给v这样的:

(v,) = the_set

如果the_set不包含确切的一项,则会引发异常。

于 2011-05-23T01:21:23.780 回答