如何递归打印列表中的数据

2024-10-01 07:35:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

哪里有问题,我找不到。我应该更换、移除什么。?你知道吗


Tags: 数据函数示例列表stringdeftypecount
3条回答

您需要将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
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

通常,将这些东西表示为生成器更容易

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)

您可以将depth/item作为元组来生成,而不是一遍又一遍地连接字符串

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))

相关问题 更多 >