Python 如何打乱列表中的顺序?

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

How to shuffle the order in a list?

pythonarrays

提问by Hiroyuki Nuri

I would like to shuffle the order of the elements in a list.

我想打乱列表中元素的顺序。

from random import shuffle
words = ['red', 'adventure', 'cat', 'cat']
shuffled = shuffle(words)
print(shuffled) # expect new order for, example ['cat', 'red', 'adventure', 'cat']

As response I get None, why?

作为我得到的回应None,为什么?

回答by vallentin

It's because random.shuffleshuffles in place and doesn't return anything (thus why you get None).

这是因为random.shuffleshuffle 到位并且不返回任何东西(这就是为什么你得到None)。

import random

words = ['red', 'adventure', 'cat', 'cat']
random.shuffle(words)

print(words) # Possible Output: ['cat', 'cat', 'red', 'adventure']

Edit:

编辑:

Given your edit, what you need to change is:

鉴于您的编辑,您需要更改的是:

from random import shuffle

words = ['red', 'adventure', 'cat', 'cat']
newwords = words[:] # Copy words
shuffle(newwords) # Shuffle newwords

print(newwords) # Possible Output: ['cat', 'cat', 'red', 'adventure']

or

或者

from random import sample

words = ['red', 'adventure', 'cat', 'cat']
newwords = sample(words, len(words)) # Copy and shuffle

print(newwords) # Possible Output: ['cat', 'cat', 'red', 'adventure']