Python。它是一个列表列表。如何使列表中的数据表示为'moreline'string'这样的函数,使每一个数据都显示在它的新行中,并且在它前面有许多'*'作为数据的深度。你知道吗
示例:我们有list[2, 4, [[3, 8], 1]]
,现在函数必须生成并返回string,哪个函数“print”像这样打印出来:
* 2
* 4
*** 3
*** 8
** 1
我现在只做了这个,它不起作用
def Function(List):
s=''
Count=0
for element in List:
Count+=1
if type(element)==type([]):
s+=Function(element)
else:
s+=Count*'*'+str(element)+('\n')
return s
如果用打印件替换退货,它会向我报告一个错误。。。但是如果我返回s并打印字符串,它就正常工作了,但又一次不是它应该如何工作
>>> Function([2, 4, [[3, 8], 1]])
'*2\n*4\n*3\n*8\n**1\n'
>>> print('*2\n*4\n*3\n*8\n**1\n')
*2
*4
*3
*8
**1
哪里有问题,我找不到。我应该更换、移除什么。?你知道吗
您需要将
count
传递给递归调用;局部变量不会神奇地传递给新函数调用:我用代码解决了其他各种问题:
Function
不是个好名字。你知道吗str.join()
;这比通过串联构建字符串要快。你知道吗isinstance()
测试特定类型。你知道吗演示:
输出:
通常,将这些东西表示为生成器更容易
在Python3.3+中,可以使用
yield from
您可以将depth/item作为元组来生成,而不是一遍又一遍地连接字符串
相关问题 更多 >
编程相关推荐