Python: .pop() on unordered sets

我们两清 提交于 2019-12-13 00:33:48

问题


I have a question regarding the .pop() method. 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()?

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?

Thanks!


回答1:


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.




回答2:


I think the best way would be to use 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().



来源:https://stackoverflow.com/questions/27952058/python-pop-on-unordered-sets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!