python用户输入列表对列表进行加法,Python列表理解加法

I'm new to Python and cannot convert a function to a list comprehension. The comprehension involves the value function, of which the containing class is as follows:

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)

A different class creates a list of Card objects, and defines the following function:

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

From what I can see, the value function is a candidate for list comprehension, but I cannot get it working. I believe the following would be correct, but I continue to get syntax errors, I have no idea what I'm doing wrong. Please note that I'm new to Python and list comprehensions:

def value(self):

result = [x += y for x = Card.values[y.rank] for y in self.cards]

解决方案

You can simply use sum function and a generator expression like this

def value(self):

return sum(Card.values[card.rank] for card in self.cards)

If you want to use list comprehension, then you can simply convert the generator expression with list comprehension syntax, like this

def value(self):

return sum([Card.values[card.rank] for card in self.cards])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值