Python随机抽取代码
以下是Python实现随机抽取的代码示例:
import random
# 创建一个列表
items = ['apple', 'banana', 'orange', 'pear', 'grape']
# 随机抽取一个元素
random_item = random.choice(items)
print(random_item)
# 随机抽取n个元素
n = 3
random_items = random.sample(items, n)
print(random_items)
# 打乱列表顺序
random.shuffle(items)
print(items)
运行结果:
pear
['grape', 'orange', 'banana']
['orange', 'pear', 'grape', 'banana', 'apple']
原文地址: https://www.cveoy.top/t/topic/gkEw 著作权归作者所有。请勿转载和采集!