Python:TypeError:无法将“生成器"对象隐式转换为str [英] Python: TypeError: Can't convert 'generator' object to str implicitly

查看:83
本文介绍了Python:TypeError:无法将“生成器"对象隐式转换为str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做作业,这是该班级的样子:

I'm doing an assignment and here is what the class looks like:

class GameStateNode:
    '''
    A tree of possible states for a two-player, sequential move, zero-sum,
    perfect-information game.

    value: GameState -- the game state at the root of this tree
    children: list -- all possible game states that can be reached from this
    game state via one legal move in the game.  children is None until grow
    is called.
    '''

    def __init__(self, game_state):
        ''' (GameStateNode, GameState) -> NoneType

        Initialize a new game state tree consisting of a single root node 
        that contains game_state.
        '''
        self.value = game_state
        self.children = []

然后我编写了这两个函数,因为我需要一个递归str:

I then wrote these two functions in because I need a recursive str:

    def __str__(self):
        ''' (GameStateNode) -> str '''    
        return _str(self)

def _str(node):
    ''' (GameStateNode, str) -> str '''
    return ((str(node.value) + '\n') + 
            ((str(child) for child in node.children) if node.children else ''))

有人可以告诉我_str函数出了什么问题吗?

Can somebody tell me what the problem is with my _str function?

推荐答案

问题是您遍历子级并将其转换为字符串的部分:

The problem is the part where you iterate over the children and convert them to strings:

(str(child) for child in node.children)

实际上是一个生成器表达式,这不能简单地转换为字符串并与左侧的 str(node.value)+'\ n'串联.

That is actually a generator expression, which can't be simply converted to a string and concatenated with the left part str(node.value) + '\n'.

在进行字符串连接之前,您可能应该通过调用 join 将由生成器创建的字符串连接为单个字符串.这样的事情将使用逗号将字符串连接起来:

Before doing the string concatenation, you should probably join the strings that get created by the generator into a single string by calling join. Something like this will join the strings using a comma:

','.join(str(child) for child in node.children)

最后,您的代码可能应该简化为类似的

In the end, your code should probably be simplified to something like

def _str(node):
    ''' (GameStateNode, str) -> str '''
    return (str(node.value) + '\n' + 
        (','.join(str(child) for child in node.children) if node.children else ''))

当然,如果需要,您可以将字符串与其他字符或字符串连接,例如'\ n'.

Of course, you can join the strings with some other character or string, like '\n', if you want to.

这篇关于Python:TypeError:无法将“生成器"对象隐式转换为str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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