Randomizing a list in Python [duplicate]

旧巷老猫 提交于 2020-05-24 21:32:25

问题


I am wondering if there is a good way to "shake up" a list of items in Python. For example [1,2,3,4,5] might get shaken up / randomized to [3,1,4,2,5] (any ordering equally likely).


回答1:


from random import shuffle

list1 = [1,2,3,4,5]
shuffle(list1)

print list1
---> [3, 1, 2, 4, 5]



回答2:


Use random.shuffle:

>>> import random
>>> l = [1,2,3,4]
>>> random.shuffle(l)
>>> l
[3, 2, 4, 1]

random.shuffle(x[, random])

Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().




回答3:


random.shuffle it!

In [8]: import random

In [9]: l = [1,2,3,4,5]

In [10]: random.shuffle(l)

In [11]: l
Out[11]: [5, 2, 3, 1, 4]


来源:https://stackoverflow.com/questions/34862378/randomizing-a-list-in-python

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