所以游戏是二十一点,我有代码片段来制作一个牌组并伸出援助之手。从甲板上,这是一个列表,我正在尝试构建一个字典,以便每个卡(来自甲板的元组)将有一个映射到它的值,根据二十一点的规则。
from random import randint
def make_deck():
deck = []
for suit in suits:
for rank in ranks:
deck.append((suit,rank))
return deck
suits = ['spades','hearts','diamonds','clubs']
ranks = ['ace','two','three','four','five','six','seven','eight','nine','ten','jack','queen','king']
deck = make_deck()
def make_hand():
hand = []
for k in range(2):
card = deck.pop(randint(0,51))
hand.append(card)
return hand
hand = make_hand()
values = {} #empty dictionary
for card in deck:
rank = [card[1] for card in deck]
if rank == 'ace':
values[card] = 1
elif rank == 'two':
values[card] = 2
elif rank == 'three':
values[card] = 3
elif rank == 'four':
values[card] = 4
elif rank == 'five':
values[card] = 5
elif rank == 'six':
values[card] = 6
elif rank == 'seven':
values[card] = 7
elif rank == 'eight':
values[card] = 8
elif rank == 'nine':
values[card] = 9
elif rank == 'ten' or 'jack' or 'queen' or 'king':
values[card] = 10
print values
显然,这是通过蛮力创建字典并且缺乏任何优雅,因此任何指向更有效的方式都将受到赞赏。真正的问题是我无法确定我的代码有什么问题,print values
只返回映射到其值的一个元组而不是整个字典。如果我在循环之外移动rank
的列表推导,我只会得到一个字典,其中所有内容都映射到值10。
另外,我刚刚意识到我的make_hand()
函数有时会导致“pop index超出范围”的错误,因此建议尝试使其始终有效的建议也将受到赞赏
答案 0 :(得分:2)
替换行:
rank = [card[1] for card in deck]
使用:
rank = card[1]
是的,你可以通过创建一个将值映射到分数的字典来更有效地(并且优雅地)实现它:
mapper = {'ace': 1, 'two': 2, ...}
然后你不需要if / elif ...... else:
for card in deck:
values[card] = mapper[card[1]]