Randomizing a list in Python [duplicate]

2020-05-27 05:33发布

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

3条回答
倾城 Initia
2楼-- · 2020-05-27 05:43
from random import shuffle

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

print list1
---> [3, 1, 2, 4, 5]
查看更多
【Aperson】
3楼-- · 2020-05-27 05:45

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

查看更多
霸刀☆藐视天下
4楼-- · 2020-05-27 06:00

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]
查看更多
登录 后发表回答