Python列表理解加法 [英] Python List Comprehension for Addition

查看:131
本文介绍了Python列表理解加法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,无法将函数转换为列表理解.理解涉及value函数,其包含的类如下:

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)

另一个类创建Card对象列表,并定义以下功能:

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

据我所知,value函数是列表理解的候选者,但是我无法使其正常工作.我相信以下内容是正确的,但我仍然会遇到语法错误,我不知道自己在做什么错.请注意,我是Python的新手,请列出以下内容:

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])

这篇关于Python列表理解加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆