python 有谁知道一种打乱列表中元素的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1524160/
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-11-03 22:28:49  来源:igfitidea点击:

Does anyone know a way to scramble the elements in a list?

pythonrandom

提问by TIMEX

thelist = ['a','b','c','d']

How I can to scramble them in Python?

我怎样才能在 Python 中打乱它们?

回答by Peter

>>> import random
>>> thelist = ['a', 'b', 'c', 'd']
>>> random.shuffle(thelist)
>>> thelist
['d', 'a', 'c', 'b']

Your result will (hopefully!) vary.

您的结果会(希望如此!)有所不同。

回答by Phil

import random
random.shuffle(thelist)

Note, this shuffles the list in-place.

请注意,这会原地打乱列表。

回答by Greg Hewgill

Use the random.shuffle()function:

使用random.shuffle()函数:

random.shuffle(thelist)

回答by RichieHindle

Use the shufflefunction from the randommodule:

使用模块中的shuffle函数random

>>> from random import shuffle
>>> thelist = ['a','b','c','d']
>>> shuffle(thelist)
>>> thelist
['c', 'a', 'b', 'd']

回答by Omar Cusma Fait

in-placeshuffle (modifies v, returns None)

就地洗牌(修改 v,返回 None)

random.shuffle(v)

not in-placeshuffle (if you don't want to modify the original array, creates a shuffled copy)

not in-placeshuffle(如果你不想修改原始数组,创建一个shuffled副本)

v = random.sample(v, len(v))