首页 > 解决方案 > 从列表中选择不同的随机项目

问题描述

我正在尝试在 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张牌中重复两次

你能帮我么?

标签: python

解决方案


使用random.samplewhich 选择唯一值:

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) 

推荐阅读