繁体   English   中英

如何从列表中添加两个项目的迭代以形成总数(二十一点手牌)

[英]How can I add two iterations of items from a list to form a total (cards from a blackjack hand)

PlayersHand 是这样设置的。

import random

PlayersHand = []
DealersHand = []
Ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10","Ace", "Jack", "Queen", "King"]
Suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
Deck = []
for num in Ranks:
    for  suit in Suits:
        card = num + ' of ' + suit
        Deck += [card]
        random.shuffle(Deck)

print()

for i in Deck:
    numval=(i[0]) 

PlayersHand = random.choices(Deck, k=2)
        print(name,"Your cards are", PlayersHand)
        DealersHand = random.choices(Deck, k=1)
        print("Dealer, your cards are Blank +",DealersHand)
        total = 0

  for i in PlayersHand:
        countval=(i[0])#to get the value of the card(perhaps need first two values for one or ten)
        print ("count is", countval);
        print("-------------")
        print(i)
    if countval == "J" or countval =="K" or countval =="Q": total +=10
    elif  countval =="A":
            total = 11
    else:
            total=countval

    print ("countval is",countval)
    print ("countval is",total)

在代码中,我添加了一些标记来帮助我理解流程。 i 值按应有的方式重复,但需要(第二个)值,我似乎无法单独获取和使用第一个值,因此我可以添加它们。 即 countval1 添加到 countval2 将成为总数然后我需要能够添加下一张新卡。

我知道有更好的方法我还不太了解(例如 dicts 等)但我想像这样完成它,因为我已经为此苦苦挣扎了这么久!

请注意,在if语句的其他两个分支中,您忘记了+ ,因此您没有添加到总数 ( += ) 中,而是覆盖了值 ( = )。

假设PlayersHand是一个可迭代的 object(即一个列表)字符串,您的代码应该如下所示:

total = 0

for i in PlayersHand:
    countval = i[:2] # up to two characters

    if countval in 'JKQ':
        total += 10
    elif countval == 'A':
        total += 11
    else:
        total += int(countval) # cast a string to a number 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM