在 Python 中随机化一个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34862378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Randomizing a list in Python
提问by amrcsu
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).
我想知道是否有一种好方法可以在 Python 中“调整”项目列表。例如,[1,2,3,4,5]
可能会被调整/随机化[3,1,4,2,5]
(任何排序的可能性都相同)。
采纳答案by roganjosh
from random import shuffle
list1 = [1,2,3,4,5]
shuffle(list1)
print list1
---> [3, 1, 2, 4, 5]
回答by bigOther
Use random.shuffle
:
使用random.shuffle
:
>>> import random
>>> l = [1,2,3,4]
>>> random.shuffle(l)
>>> l
[3, 2, 4, 1]
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().
将序列 x 原地打乱。可选参数 random 是一个 0 参数函数,返回 [0.0, 1.0) 中的随机浮点数;默认情况下,这是函数 random()。
回答by bakkal
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]