从Python中的字典中获取随机值

时间:2017-06-22 12:15:51

标签: python python-2.7 random

如何从dict获得随机对?我在黑杰克上制作游戏,因此用户可以从

获得随机对
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}

它将存储在字典

player_deck = {}

我该怎么做?

5 个答案:

答案 0 :(得分:3)

使用random.choice()

import random
player_deck = {}
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}

key, value = random.choice(list(deck_of_cards.items()))
player_deck[key] = value

或者,如果您想将键和值直接放入字典中,可以像这样执行

player_deck = dict([random.choice(list(deck_of_cards.items()))])

答案 1 :(得分:1)

使用random.choice

import random
player_deck = {}
deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
d = random.choice(list(deck_of_cards.items()))
player_deck.update(d)
print(player_deck)
{'9': 9}

答案 2 :(得分:1)

你想要用这个词来模拟一个牌组并不是很清楚。

如果你只是多次使用random.choice,你可能会获得相同的卡两次,这可能不会发生。

你可以创建一个整个牌组(作为一个列表,而不是作为一个词典),shuffle它,画一张牌(从而将其从牌组中移除),并检查它的价值。 使用Card定义一个新的namedtuple课程并不太难,之后可以更轻松地使用它(感谢@MaartenFabré的评论):

# encoding: utf-8
import random
from collections import namedtuple


class Card(namedtuple('Card', ['face', 'color'])):
    colors = ['♠', '♥', '♦', '♣']
    faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
    values = dict(zip(faces, [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]))

    def __repr__(self):
        return self.face + self.color

    def value(self):
        return Card.values[self.face]

    @staticmethod
    def all():
        return [Card(face, color)
                for color in Card.colors for face in Card.faces]

deck = Card.all()

print(deck)
# ['A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠', 'A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣']

random.shuffle(deck)

print(deck)
# ['9♣', '4♠', 'J♥', '9♦', '10♠', 'K♣', '8♥', '3♣', 'J♣', '10♦', '8♦', 'A♣', '7♦', '3♠', '7♠', 'Q♣', '7♥', 'Q♦', 'A♦', '9♥', '2♠', '7♣', '6♦', '4♣', 'Q♠', '3♥', 'K♠', '6♣', '5♦', '4♥', '5♣', '2♣', '2♥', '6♥', '8♠', '2♦', '4♦', '8♣', 'K♦', '10♥', 'K♥', '5♠', 'J♦', '5♥', 'A♥', '9♠', '6♠', 'Q♥', '10♣', 'A♠', '3♦', 'J♠']

a_card = deck.pop()
print(a_card)
# J♠
print(a_card.face)
# J
print(a_card.color)
# ♠
print(a_card.value())
# 10

答案 3 :(得分:0)

您可以这样做:

import random

deck_of_cards = {'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
player_deck = dict(random.sample(deck_of_cards.items(),1))

我基本上要求字典中的'1'随机样本并将输出强制转换为字典(因为它返回一个列表)。

希望这有帮助!

答案 4 :(得分:0)

您可以使用random.choice

    import random
    player_deck=[]
    player_deck.append(random.choice(list(deck_of_cards.items())))
    print(player_deck)