python - 没有重复元素的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)
解决方案
您可以使用random.sample
:
liste2 = random.sample(liste, 4)
print(liste2)
输出:
['Ultramarine', 'Green', 'Blue', 'Purple']
推荐阅读
- c# - 在 C# 中编码用于反序列化的 xml
- php - 从由 Digital Ocean 上的反向代理链接的 docker 容器中的静态站点发送电子邮件
- python - 如何通过 Selenium 和 Python 在嵌套的 div 标签中找到按钮?
- amazon-web-services - 使用无服务器将 aws sqs 添加为 aws lambda 函数触发器
- firebase - Firebase 函数:ReferenceError:decodedToken 未定义
- mongodb - Mongo 聚合在 3.4.7 版本中将字符串转换为日期
- c - for 循环中的 AT 命令
- react-native - ReactNative TextView 中的链接
- powershell - Login-AzureRMAccount noninteractive 使用组织帐户失败
- dart - 未收到堆栈边界外的手势响应