【问题标题】:How to pull out values from a dictionary into an array如何将字典中的值提取到数组中
【发布时间】:2016-01-14 12:31:31
【问题描述】:
spades = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS']
hearts = ['2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH']
clubs = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC']
diamonds = ['2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD']
allCards = spades + hearts + clubs + diamonds

import random
random.shuffle(allCards)

bot1 = [allCards.pop() for i in range(2)]
print(bot1)
cardVal = {'2S':1,'3S':2,'4S':3,'5S': 4,'6S':5,'7S':6,'8S':7,'9S':8,'10S':9,'JS':10,'QS':11,'KS':12,'AS':13,
    '2H':1,'3H':2,'4H':3,'5H': 4,'6H':5,'7H':6,'8H':7,'9H':8,'10H':9,'JH':10,'QH':11,'KH':12,'AH':13,
    '2C':1,'3C':2,'4C':3,'5C': 4,'6C':5,'7C':6,'8C':7,'9C':8,'10C':9,'JC':10,'QC':11,'KC':12,'AC':13,
    '2D':1,'3D':2,'4D':3,'5D': 4,'6D':5,'7D':6,'8D':7,'9D':8,'10D':9,'JD':10,'QD':11,'KD':12,'AD':13}

for i in bot1:
    print(cardVal[i])
    bot1hand = [cardVal[i]]
print(bot1hand)

我想将bot1 拥有的卡片的值放在一个单独的数组中,但遇到了问题。我总是将这两个值打印在不同的行上,而数组bot1hand 只存储这两个值的最后一个值。

例如:

>>> 
['AC', '5C']
13
4
[4]
>>> 

【问题讨论】:

    标签: python arrays dictionary


    【解决方案1】:

    你的问题就在这里:

    for i in bot1:
        print(cardVal[i])
        bot1hand = [cardVal[i]]
    print(bot1hand)
    

    尤其是这一行:

    bot1hand = [cardVal[i]]
    

    你一直在重写你的价值观,因为你实际上并没有正确地附加到你的列表中。事实上,您的 bot1hand 并未被视为列表。

    您首先要做的是将其初始化为循环之外的列表:

    bot1hand = []
    

    然后在你的循环中,使用 append 方法:

    bot1hand.append(cardVal[i])
    

    所以你的最后一段代码应该是这样的:

    bot1hand = []
    for i in bot1:
        print(cardVal[i])
        bot1hand.append(cardVal[i])
    print(bot1hand)
    

    作为代码中的最后一个重构步骤,您实际上可以执行@NathanielFord 建议的操作,即使用理解(我看到您已经在代码中使用了它,所以您必须已经熟悉它)。我在这个答案中的那段代码现在可以简化为:

    bot1hand = [cardVal[i] for i in bot1]
    

    【讨论】:

      【解决方案2】:

      您的for 循环是问题所在。您可能想尝试列表comprehension

      bot1hand = [cardVal[i] for i in bot1]
      print(bot1hand)
      

      (我假设 print 语句是出于调试目的。)

      列表理解处理实际为您构建列表的责任。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多