【问题标题】:.popitem() selecting the exact same pairs from dictionary every time the code is run.popitem() 每次运行代码时从字典中选择完全相同的对
【发布时间】:2017-11-09 13:47:30
【问题描述】:

我需要在两个电脑玩家之间进行二十一点游戏。我知道该怎么做,但我无法弄清楚这个错误 每次我分配要发给玩家的牌时,它都会正确累积总数,但每次都会抽相同的牌。

代码在这里

deck = {'Ace of Spades':1, '2 of Spades':2, '3 of Spades':3,
        '4 of Spades':4, '5 of Spades':5, '6 of Spades':6,
        '7 of Spades':7, '8 of Spades':8, '9 of Spades':9,
        '10 of Spades':10, 'Jack of Spades':10,
        'Queen of Spades':10, 'King of Spades': 10,

        'Ace of Hearts':1, '2 of Hearts':2, '3 of Hearts':3,
        '4 of Hearts':4, '5 of Hearts':5, '6 of Hearts':6,
        '7 of Hearts':7, '8 of Hearts':8, '9 of Hearts':9,
        '10 of Hearts':10, 'Jack of Hearts':10,
        'Queen of Hearts':10, 'King of Hearts': 10,

        'Ace of Clubs':1, '2 of Clubs':2, '3 of Clubs':3,
        '4 of Clubs':4, '5 of Clubs':5, '6 of Clubs':6,
        '7 of Clubs':7, '8 of Clubs':8, '9 of Clubs':9,
        '10 of Clubs':10, 'Jack of Clubs':10,
        'Queen of Clubs':10, 'King of Clubs': 10,

        'Ace of Diamonds':1, '2 of Diamonds':2, '3 of Diamonds':3,
        '4 of Diamonds':4, '5 of Diamonds':5, '6 of Diamonds':6,
        '7 of Diamonds':7, '8 of Diamonds':8, '9 of Diamonds':9,
        '10 of Diamonds':10, 'Jack of Diamonds':10,
        'Queen of Diamonds':10, 'King of Diamonds': 10}

hand_1 = 'string'
hand_1_value = 0
hand_1_total = 0

hand_2 = 'string'
hand_2_value = 0
hand_2_total = 0

while hand_1_total < 21:
    k, v = deck.popitem()
    hand_1 = k
    hand_1_total = hand_1_total + v

    print('Player 1 is dealt', hand_1)
    print('Player 1 score is',hand_1_total)

在这里输出:

Player 1 is dealt King of Diamonds
Player 1 score is 10
Player 1 is dealt Queen of Diamonds
Player 1 score is 20
Player 1 is dealt Jack of Diamonds
Player 1 score is 30

每次我运行它时,它都会分配皇家钻石套装,我不知道为什么?我的教科书说 dict.popitem() 返回一个随机选择的键:值对作为声明变量的元组。

我的第一个想法是,作为一个元组,变量在第一次迭代时无法更改。但这对我来说并不正确,也无法解释为什么每次都选择相同的卡片。

【问题讨论】:

  • 这是任意的,而不是随机的
  • @LevLevitsky 那么我需要导入随机模块吗?我的课本特别说是随机选的,所以才提到。
  • 是的,您需要使用random.choice 之类的名称。如果您的教科书使用“随机”一词,那是不正确的。 docs 中使用的词是“任意的”,您会看到有什么区别。

标签: python dictionary random


【解决方案1】:

您将获得相同的模式,因为deck.popitem()deck.items() 中的元素顺序返回项目。

由于您的deck 每次都相同,deck.items() 也相同,因此popitem() 以相同的顺序返回元素。

一种随机化的方法是:

import random
..
..
items = list(deck.items())
random.shuffle(items)
for k,v in items:
    hand_1 = k
    hand_1_total = hand_1_total + v

    print('Player 1 is dealt', hand_1)
    print('Player 1 score is',hand_1_total)

【讨论】:

  • 我现在明白了,我向我的导师发送了关于这本书的描述的信息。所以 k, v 应该传递相应的对吗?或者它会从一个元素中分配一个随机键,而从另一个元素中分配一个完全不同的值?
  • shuffle(items) 列表中 (k,v) 对的顺序是随机的。在 for 循环中,您每次都会得到不同的 (k,v) 对
猜你喜欢
  • 2021-06-18
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2012-10-03
  • 2021-12-20
相关资源
最近更新 更多