用于random.shuffle()
就地打乱列表:
import random
words = ["python", "java", "constant", "immutable"]
random.shuffle(words)
print(*words)
input('')
演示:
>>> import random
>>> words = ["python", "java", "constant", "immutable"]
>>> random.shuffle(words)
>>> words
['python', 'java', 'constant', 'immutable']
如果你想保留words
(保持顺序),你可以使用sorted()
随机键来返回一个新的随机列表:
words = ["python", "java", "constant", "immutable"]
print(*sorted(words, key=lambda k: random.random()))
这words
保持不变:
>>> words = ["python", "java", "constant", "immutable"]
>>> sorted(words, key=lambda k: random.random())
['immutable', 'java', 'constant', 'python']
>>> words
['python', 'java', 'constant', 'immutable']