在卡列表中选择多个随机项

0 python random

我想从同一个列表中选择两个单独的随机选项.有没有办法做到这一点,不包括制作单独的名单?

import random


cards = [2,3,4,5,6,7,8,9,10,'King','Queen','Jack']
cards = random.choice(cards)

suits = ['Clubs', 'Hearts', 'Spades', 'Diamonds']
suits = random.choice(suits)

first_card = ("your first card is the {} of {}") .format(cards,suits)
second_card = ("your second card is the {} of {}") .format(cards,suits)

print first_card
print second_card
Run Code Online (Sandbox Code Playgroud)

产量

your first card is the 10 of Spades
your second card is the 10 of Spades
Run Code Online (Sandbox Code Playgroud)

我希望输出相同,但最后一张牌与第一张牌不同; 两张单独的卡片

Oli*_*çon 5

事先,通过例如列表理解,从数字和套装生成所有卡片.然后random.sample用来挑选两张随机卡片.

import random

figures = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'King', 'Queen', 'Jack']
suits = ['Clubs', 'Hearts', 'Spades', 'Diamonds']

cards = [(figure, suit) for figure in figures for suit in suits]

print(random.sample(cards, 2)) # [(5, 'Hearts'), (7, 'Diamonds')]
Run Code Online (Sandbox Code Playgroud)

虽然,我建议你不要混合整数和字符串来定义你的数字,因为这可能会导致一些混乱.我建议你指定的整数11,12并且13Jack,QueenKing分别.