的Python。给出列表清单。如何使列表中的数据表示像'moreline'字符串'这样的函数,就像每个数据都会在新行中显示一样,而在它前面的数据就像数据深度那么多'*'。
示例:我们有列表[2, 4, [[3, 8], 1]]
,现在函数必须生成并返回字符串,函数'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
问题在哪里,我找不到。我该怎么替换,删除等?
答案 0 :(得分:1)
您需要将count
传递给递归调用;局部变量不会神奇地转移到新的函数调用:
def format_nested(lst, depth=1):
s = []
for element in lst:
if isinstance(element, list):
s.append(print_nested(element, depth + 1))
else:
s.append('{0} {1}\n'.format(depth * '*', element))
return ''.join(s)
我用代码解决了其他各种问题:
Function
不是一个好名字。str.join()
;它比通过连接构建字符串更快。isinstance()
测试特定类型。演示:
>>> format_nested([2, 4, [[3, 8], 1]])
'* 2\n* 4\n*** 3\n*** 8\n** 1\n'
>>> print format_nested([2, 4, [[3, 8], 1]])
* 2
* 4
*** 3
*** 8
** 1
答案 1 :(得分:1)
def r(l, depth=0, ret=[]):
if isinstance(l,list):
for i in l:
r(i, depth+1)
else:
ret.append('*' * depth + str(l))
return ret
print '\n'.join(r([2, 4, [[3, 8], 1]]))
输出:
*2
*4
***3
***8
**1
答案 2 :(得分:0)
通常将这些东西表达为生成器更容易
L = [2, 4, [[3, 8], 1]]
def nest_gen(L):
if isinstance(L, list):
for i in L:
for j in nest_gen(i):
yield "*"+str(j)
else:
yield L
for row in nest_gen(L):
print(row)
在Python3.3 +中,您可以使用yield from
L = [2, 4, [[3, 8], 1]]
def nest_gen(L):
if isinstance(L, list):
yield from ("*"+str(j) for i in L for j in nest_gen(i))
else:
yield L
for row in nest_gen(L):
print(row)
不是反复链接字符串,而是将深度/项目作为元组产生
L = [2, 4, [[3, 8], 1]]
def nest_gen(L):
if isinstance(L, list):
yield from ((j+1, k) for i in L for j, k in nest_gen(i))
else:
yield 0, L
for item in nest_gen(L):
print("{:*>{}} {}".format('', *item))