我正在做一个练习来压缩嵌套列表.代码在控制台中工作,但它在文件中时不起作用.我不知道是怎么回事.:(
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()
Run Code Online (Sandbox Code Playgroud)
我首先尝试递归地解决这个练习但决定先尝试迭代.
编辑:在文件中执行时,它只打印出原始函数参数TIA
问题是你的展平功能只会使一个级别变平.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]
Run Code Online (Sandbox Code Playgroud)
你应该研究一种递归方法而不是追加 y- 你也可以调平y.if type(x) != type([])可以是你的基础案例.