在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:38:43  来源:igfitidea点击:

Randomizing a list in Python

pythonlistrandom

提问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]

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().

random.shuffle(x[, 随机])

将序列 x 原地打乱。可选参数 random 是一个 0 参数函数,返回 [0.0, 1.0) 中的随机浮点数;默认情况下,这是函数 random()。

回答by bakkal

random.shuffleit!

随机洗牌吧!

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]