Python:展平函数在控制台中有效但在文件中无效?

标签 python flatten

我正在做一个练习来展平嵌套列表。该代码在控制台中有效,但在文件中时无效。我不知道发生了什么事。 :(

def flatten(nested):
    """
            >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]])
            [2, 9, 2, 1, 13, 2, 8, 2, 6]
            >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]])
            [9, 7, 1, 13, 2, 8, 7, 6]
            >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]])
            [9, 7, 1, 13, 2, 8, 2, 6]
            >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]])
            [5, 5, 1, 5, 5, 5, 5, 6]
    """
    simple = []

    for x in nested:
            if type(x) == type([]):
                    for y in x:
                            simple.append(y)
            else:
                    simple.append(x)
    return simple



if __name__ == '__main__':
    import doctest
    doctest.testmod()

我首先尝试递归地解决这个练习,但决定先尝试迭代。

编辑:在文件中执行时,它只是打印出原始函数参数 时间差

最佳答案

问题是您的 flatten 函数只展平了一层。 doctest之所以打印出错误,是因为它确实在报错。它们不是您传入的内容。

File "test.py", line 5, in __main__.flatten
Failed example:
    flatten([[9, [7, 1, 13, 2], 8], [7, 6]])
Expected:
    [9, 7, 1, 13, 2, 8, 7, 6]
Got:
    [9, [7, 1, 13, 2], 8, 7, 6]

您应该研究一种递归方法,而不是附加 y--- 您也可以在 y 上调用 flatten。 if type(x) != type([]) 可以作为您的基本情况。

关于Python:展平函数在控制台中有效但在文件中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3240929/

相关文章:

mongodb - 是否可以展平 MongoDB 结果查询?

regex - 如何通过将行旋转为 csv 数据来折叠工作表

c# - AutoMapper 和展平嵌套数组

java - 是否鼓励在 Java 中使用多处理池?我有正在转换为 Java 的 Python 代码

iphone - 如何从 UILabel 创建图像?

python Popen : How do I block the execution of grep command until the content to grep is ready?

python - python中的一致备份

javascript - 用于递归展平结果的 JS 数组串联

python - img 不是 numpy 数组,也不是标量

python - 为什么访问 numpy 数组中的一个元素会使我的程序速度减慢这么多?