首页 > 解决方案 > 没有重复元素的Python随机函数

问题描述

有美好的一天。

这是我的问题。我有 8 种颜色,我想随机选择 4 种不同的颜色。我随机选择了 4 种颜色,但颜色重复。如何修复并改进我的代码?

我的代码:

import random
r = "Red"
o = "Orange"
y = "Yellow"
g = "Green"
b = "Blue"
p = "Purple"
m = "Maroon"
u = "Ultramarine"

liste = [r,o,y,g,b,p,m,u]
liste2 = [random.choice(liste) +  random.choice(liste) + random.choice(liste) + random.choice(liste)]
print(liste2)

标签: python

解决方案


您可以使用random.sample

liste2 = random.sample(liste, 4)
print(liste2)

输出:

['Ultramarine', 'Green', 'Blue', 'Purple']

推荐阅读