我想从同一个列表中选择两个单独的随机选项。有没有办法做到这一点,不包括制作单独的名单?
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
your first card is the 10 of Spades
your second card is the 10 of Spades
我希望输出相同,但最后一张牌与第一张牌不同;两张单独的卡
答案 0 :(得分: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')]
虽然,我建议你不要混合整数和字符串来定义你的数字,因为这可能会导致一些混乱。我建议您将整数11
,12
和13
分别分配给Jack
,Queen
和King
。
答案 1 :(得分:0)
你可以使用itertools生成所有组合然后随机播放列表并取两个,我为n_samples设计了函数你可以选择n个样本:
import random
import itertools
cards = [2,3,4,5,6,7,8,9,10,'King','Queen','Jack']
suits = ['Clubs', 'Hearts', 'Spades', 'Diamonds']
def n_random(list_1,list_2,no_of_samples):
all_possible=[i for i in itertools.product(list_1,list_2)]
if no_of_samples>len(all_possible):
return 'Wrong choice'
else:
random.shuffle(all_possible)
return all_possible[:2]
print(n_random(cards,suits,2))
输出:
[(3, 'Diamonds'), (2, 'Spades')]
答案 2 :(得分:-1)
使用random.sample
。
random.sample(population, k)
:
返回从人口序列或集合中选择的唯一元素的k
长度列表。
import random
cards = [2,3,4,5,6,7,8,9,10,'King','Queen','Jack']
chosen_cards = random.sample(cards,2)
suits = ['Clubs', 'Hearts', 'Spades', 'Diamonds']
chosen_suits = random.sample(suits,2)
first_card = ("your first card is the {} of {}") .format(chosen_cards[0],chosen_suits[0])
second_card = ("your second card is the {} of {}") .format(chosen_cards[1],chosen_suits[1])
print(first_card)
print(second_card)
答案 3 :(得分:-3)
每次都可以保证使用不同的卡片:
from random import randint
cards = [2,3,4,5,6,7,8,9,10,'King','Queen','Jack']
first_card = cards[randint(0, len(cards)-1)]
second_card = cards[randint(0, len(cards)-1)]
while second_card == first_card:
second_card = cards[randint(0, len(cards)-1)]
print first_card
print second_card