python - 从列表中选择不同的随机项目
问题描述
我正在尝试在 python 3.8 中制作一个拉米程序,并且有一个包含所有可能卡片的列表,我如何选择 13 张随机不同的卡片,这样一旦玩家选择了这些卡片,其他玩家就无法收到它们?
例如
card =['Ah','Ad','Ac','As','2h','2d','2c','2s','3h','3d','3c','3s','4h','4d','4c','4s','5h','5d','5c','5s','6h','6d','6c','6s','7h','7d','7c','7s','8h','8d','8c','8s','9d','9c','9h','9s','10h','10d','10c','10s','Jh','Jd','Jc','Js','Qh','Qd','Qc','Qs','Kh','Kd','Kc','Ks','Joker1','Joker2']
n1=[random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),random.choice(card),]
如果这个命令做完,牌不分明,Kc可以在13张牌中重复两次
你能帮我么?
解决方案
使用random.sample
which 选择唯一值:
from random import sample
card = ['Ah','Ad','Ac','As','2h','2d','2c','2s','3h','3d','3c','3s','4h','4d','4c','4s','5h','5d','5c','5s','6h','6d','6c','6s','7h','7d','7c','7s','8h','8d','8c','8s','9d','9c','9h','9s','10h','10d','10c','10s','Jh','Jd','Jc','Js','Qh','Qd','Qc','Qs','Kh','Kd','Kc','Ks','Joker1','Joker2']
# e.g.
player_1_selected = sample(card, 13)
# ['5s', '10c', 'As', '2h', 'Qh', 'Kc', '10s', '4h', 'Qc', '9h', '8c', '4d', '3s']
print(player_1_selected)
remaining_to_select = list(set(card) - set(player_1_selected))
# ['3c', 'Ac', 'Qs', '6h', '9s', '7s', '5c', '3h', 'Ad', 'Qd', '9d', '7h', '10d', '6d', '2d', '3d', '5h', '7d', '6c', 'Kd', '2s', 'Jh', '8s', '9c', 'Kh', '6s', 'Ah', '10h', 'Jd', '7c', 'Ks', '4c', '2c', 'Joker2', '8h', '8d', 'Jc', 'Js', 'Joker1', '5d', '4s']
print(remaining_to_select)
推荐阅读
- python-3.x - Selenium python Chrome - 动作类不发送_keys
- javascript - 修改父构造函数不影响子
- c# - Bot Framework v4 Bot 模拟器身份验证错误请求
- microsoft-graph-api - Microsoft Graph DELETE 订阅请求失败
- html - 基本(所有)链接标签是否需要 aria-label?
- angular - Angular 7 PWA - 离线模式下缺少字体真棒图标
- c++ - 为以命令式风格编写的 C 程序实现 OO 接口的模式
- javascript - Knockout JS:在 foreach 绑定中添加表单
- javascript - 如何禁用除一个以外的所有按钮,然后使用 jQuery 单击启用所有按钮?
- laravel - CKeditor 5 与 Laravel 图片上传