【发布时间】:2014-07-05 18:10:27
【问题描述】:
我是 Python 新手,无法将函数转换为列表推导式。推导涉及到value函数,其包含类如下:
class Card(object):
# Lists containing valid candidates for a card's rank and suit.
suits = [None, "spade", "club", "heart", "diamond"]
ranks = [None, "ace", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "jack", "queen", "king"]
# Dictionary containing the ranks and their associative values.
values = {None:0, "ace":1, "two":2, "three":3, "four":4,
"five":5,"six":6,"seven":7, "eight":8,"nine":9,
"ten":10, "jack":10, "queen":10, "king":10}
def __init__(self, rank=None, suit=None):
"""Constructor."""
if rank not in self.ranks:
raise ValueError("Invalid rank.")
if suit not in self.suits:
raise ValueError("Invalid suit.")
self.rank = rank
self.suit = suit
def __str__(self):
"""A string representation of the Card."""
return "{0}:{1}".format(self.rank, self.suit)
另一个类创建一个 Card 对象列表,并定义以下函数:
def value(self):
"""Returns an int value containing the summed values of the hand's cards."""
result = 0
for card in self.cards:
result += Card.values[card.rank]
return result
据我所知,value 函数是列表理解的候选者,但我无法让它工作。我相信以下内容是正确的,但我继续遇到语法错误,我不知道我做错了什么。请注意,我是 Python 和列表推导的新手:
def value(self):
result = [x += y for x = Card.values[y.rank] for y in self.cards]
【问题讨论】: