[英]Python: .pop() on unordered sets
I have a question regarding the .pop() method. 我对.pop()方法有疑问。 In the documentation, it states that on sets:
在文档中,它声明了以下内容:
Remove and return an arbitrary element from the set.
从集合中删除并返回任意元素。
So what exactly does "arbitrary" mean? 那么“任意”到底是什么意思? Like, for example: If I wanted to build a queue from a list of users where position is determined at random, could I enter in all users into a set, and then build a randomly assigned queue using .pop()?
例如,例如:如果我想从随机确定位置的用户列表中构建队列,是否可以将所有用户输入集合中,然后使用.pop()构建随机分配的队列?
So the code would look something like 所以代码看起来像
queue_set = {'bob','rachel','sara','david'}
queue = dequeue([])
while queue_set:
queue.append(queue_set.pop())
Would that be a reasonable way to randomly assign members to an index? 这是将成员随机分配给索引的合理方法吗? Or is the .pop() reliant on some way the data is entered or something?
还是.pop()依赖输入数据的某种方式?
Thanks! 谢谢!
No. 没有。
"Arbitrary" means the implementation returns whichever element is most convenient. “任意”表示实现返回最方便的元素。 You are not guaranteed randomness.
您不能保证随机性。 Use
random.sample()
or random.shuffle()
if you need random selection. 如果需要随机选择,请使用
random.sample()
或random.shuffle()
。
I think the best way would be to use random.shuffle
我认为最好的方法是使用
random.shuffle
>>> import random
>>> li = ["bob", "rachel", "sara", "david"]
>>> random.shuffle(li)
>>> li
['sara', 'bob', 'david', 'rachel']
If you want to get the elements one by one, you can then use li.pop()
. 如果要一一获取元素,则可以使用
li.pop()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.