如何调整字符串列表顺序?

Hir*_*uri 12 python arrays

我想把我的名单中的字符串放进去,

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

预期结果 :

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

我尝试使用随机库中的shuffle,但它给了我一个None错误.

我尝试了什么:

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

Val*_*tin 32

这是因为random.shuffle洗牌并没有返回任何东西(因此你得到的原因None).

import random

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

print(words) # Possible Output: ['cat', 'cat', 'red', 'adventure']
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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']
Run Code Online (Sandbox Code Playgroud)

要么

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']
Run Code Online (Sandbox Code Playgroud)

  • @Lindow您可能已经做到了,例如`words = random.shuffle(words)或`print(random.shuffle(words))`,这就是为什么它不打印`None`的原因。 (2认同)