【问题标题】:Python: TypeError: Can't convert 'generator' object to str implicitlyPython:TypeError:无法将“生成器”对象隐式转换为 str
【发布时间】:2015-04-03 05:35:31
【问题描述】:

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

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:

    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 函数有什么问题?

【问题讨论】:

    标签: python string generator typeerror


    【解决方案1】:

    问题在于您遍历子元素并将它们转换为字符串的部分:

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

    那其实是一个generator expression,不能简单的转换成字符串和左边的str(node.value) + '\n'拼接起来。

    在进行字符串连接之前,您可能应该通过调用join 将生成器创建的字符串连接成一个字符串。像这样的东西将使用逗号连接字符串:

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

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

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

    当然,如果您愿意,您可以将字符串与其他字符或字符串连接起来,例如“\n”。

    【讨论】:

    • 有效!谢谢一百万!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2017-08-31
    • 2012-11-19
    • 2015-12-10
    • 2014-08-03
    • 2017-08-24
    相关资源
    最近更新 更多