问题
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