我只是在学习python(在VBA中有背景)。
这个字典为什么不加载?我正试图拿出一副纸牌。
这是我的代码:
class Deck:
def load_deck(self):
suite = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
rank = (2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace")
full_deck={}
for s in suite:
for r in rank:
full_deck.setdefault(s,r)
return full_deck
raw_deck = Deck()
raw_deck1 = raw_deck.load_deck()
print raw_deck1
这是我的输出:
{'Hearts': 2, 'Clubs': 2, 'Spades': 2, 'Diamonds': 2}
答案 0 :(得分:3)
JBernardo的评论为您提供setdefault()
的正确用法,但您可以将循环简化为以下内容:
full_deck = {}
for s in suite:
full_deck[s] = rank
或者,如果您想要列表而不是元组,请使用list(rank)
。
一衬垫:
full_deck = {s: rank for s in suite}
Python 2.6或更低版本:
full_deck = dict((s, rank) for s in suite)
答案 1 :(得分:1)
你正在制作的方法实际上不需要在一个类中 - 取决于你想要做什么...如果你只是想填充一个字典,那么你可以分配值而不是使用setdefault()方法(如上所述)。
你可以这样做:
cards = {}
for suit in ('Heart', 'Club', 'Spade', 'Diamond'):
cards[suit] = range(2, 11) + ['Jack', 'Queen', 'King', 'Ace']
print cards
如果您尝试使用信息填充新的类类型,那么您应该定义一个 init 函数(在Python中充当类构造函数)来创建和存储新的成员变量,即:
class Deck:
def __init__( self ):
self._cards = {}
for suit in ('Heart', 'Club', 'Spade', 'Diamond'):
self._cards[suit] = range(2, 11) + ['Jack', 'Queen', 'King', 'Ace']
def cards( self ):
return self._cards
deck = Deck()
print deck.cards()
答案 2 :(得分:0)
使用来自@ernie的回复指出我需要一个带有单个密钥的字典,用于52个单独的对,我想出了以下内容,它可以实现我想要的效果。
def load_deck():
suite = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
rank = ('2', '3', '4', '5', '6', '7', '8', '9', '10', "Jack", "Queen", "King", "Ace")
full_deck = {}
i = 0
for s in suite:
for r in rank:
full_deck[i] = r,s # took this solution from the comment below. it works.
i += 1
return full_deck
print load_deck()
答案 3 :(得分:0)
这是在Python 2.7中支持词典理解的有效方法:
def load_deck():
suite = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
rank = ('2', '3', '4', '5', '6', '7', '8', '9', '10', "Jack", "Queen", "King", "Ace")
return {item[0]:item[1] for item in enumerate(((r,s) for r in rank for s in suite))}
对于Python< 2.7您需要使用另一个生成器表达式和dict
类构造函数,如下所示:
def load_deck():
suite = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
rank = ('2', '3', '4', '5', '6', '7', '8', '9', '10', "Jack", "Queen", "King", "Ace")
return dict((item[0],item[1])
for item in enumerate(((r,s) for r in rank for s in suite)))