下面的处理是为了解析变量C
以填充4个字典SHD和C.我认为问题出现在代码的倒数第二行,我在其中使用dealList
,其中套装是循环的通过。
所有套装SHD和C都被初始化为空字典,但最终包含13个字典项目,每个套装对应一套。
我怀疑发生的事情是,每次执行eval(suit)时,它会找到要处理的字典但不保留字典的名称,因此不会更新所需的命名字典。换句话说,看起来我正在使用从列表中取得的字母eval(suit)
来迭代循环,但该字母也命名为字典。但我不知道如何告诉python两者是否相关。
我需要使用什么代替eval(),或者除了eval()以实现我的目标?
S
也许输出列表会显示问题。请注意,在下面的示例输出列表中,前5张卡片是黑桃,接下来的2张卡片是心脏,心脏的K和Q是具体的。但黑桃字典正在改变,而不是心灵字典。正在更新的阵列的这种缺乏变化将永远持续下去。
keys = list('23456789TJQKA')
values = range (13)
suitDict = {}
for key,value in zip(keys, values):
suitDict[key] = value
dealList = 'AQJT5.KQ.8.KQT95 3.A765.QT743.843 974.T93.J92.AJ62 K862.J842.AK65.7'.split()
players = list('NESW')
suits = list('SHDC')
S = H = D = C = {}
playerHand ={}
for player,hand in zip(players,dealList):
playerHand[player]=hand
print player,hand
for suit,cards in zip(suits,playerHand[player].split('.')):
print "SC:",suit,cards
for card in cards:
eval(suit)[suitDict[card]]= player
print "card",card,"Suit",suit,"X",eval(suit),"card",suitDict[card],"player",player
答案 0 :(得分:1)
您的代码奇怪主要是由于您的所有西装词典(S
,H
,D
和C
)引用了相同的词典。如果您希望它们指向不同的引用(例如S, H, D, C = {}, {}, {}, {}
),则需要单独初始化它们。
话虽如此,eval
(几乎)绝不是解决方案。在你的情况下,我会做类似的事情:
keys = list('23456789TJQKA')
values = range (13)
suitDict = {}
for key,value in zip(keys, values):
suitDict[key] = value
dealList = 'AQJT5.KQ.8.KQT95 3.A765.QT743.843 974.T93.J92.AJ62 K862.J842.AK65.7'.split()
players = list('NESW')
suits = {"S": {}, "H": {}, "D": {}, "C": {}}
playerHand = {}
for player,hand in zip(players,dealList):
playerHand[player] = hand
print player,hand
for suit,cards in zip(suits,playerHand[player].split('.')):
print "SC:",suit,cards
for card in cards:
suits[suit][suitDict[card]] = player
print "card",card,"Suit",suit,"X",suits[suit],"card",suitDict[card],"player",player
话虽如此,我认为你的案件过于复杂......