Python random 模块

Python random.shuffle() 函数用于原地打乱列表顺序,返回 None。

语法

random.shuffle(lst)

参数

lst:列表。

返回值

无返回值(返回 None)。原地打乱列表顺序。

示例

import random

cards = ["A", "2", "3", "4", "5"]
random.shuffle(cards)
print(cards)          # 顺序被打乱

# 注意:shuffle 原地修改,返回 None
result = random.shuffle(cards)
print(result)         # None

# 抽题打乱顺序
questions = ["q1", "q2", "q3", "q4"]
random.shuffle(questions)
print(questions)

注意事项

shuffle 原地修改返回 None(别赋值给变量)。想打乱后保留原列表,先 copy 再 shuffle。