如何从冻结集中获取任意元素? [英] How to get an arbitrary element from a frozenset?
问题描述
我想从冻结集中获取一个元素(当然,不修改它,因为frozensets是不可变的)。到目前为止我找到的最佳解决方案是:
I would like to get an element from a frozenset (without modifying it, of course, as frozensets are immutable). The best solution I have found so far is:
s = frozenset(['a'])
iter(s).next()
按预期返回:
'a'
换句话说,有没有任何方法可以从冻结集中弹出一个元素而不实际弹出它?
In other words, is there any way of 'popping' an element from a frozenset without actually popping it?
推荐答案
(总结评论中给出的答案)
您的方法与任何方法一样好,但需要注意的是,从Python 2.6开始,您应该使用 next(iter(s))
而不是 iter(s).next()
。
Your method is as good as any, with the caveat that, from Python 2.6, you should be using next(iter(s))
rather than iter(s).next()
.
如果您想要随机元素而不是任意元素,请使用以下内容:
If you want a random element rather than an arbitrary one, use the following:
import random
random.sample(s, 1)[0]
以下几个例子展示了这两者之间的区别:
Here are a couple of examples demonstrating the difference between those two:
>>> s = frozenset("kapow")
>>> [next(iter(s)) for _ in range(10)]
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
>>> import random
>>> [random.sample(s, 1)[0] for _ in range(10)]
['w', 'a', 'o', 'o', 'w', 'o', 'k', 'k', 'p', 'k']
这篇关于如何从冻结集中获取任意元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!