简体   繁体   English

如何使用递归从列表列表中打印数据

[英]How to print data from list of list with recursion

Python. 蟒蛇。 It is given list of list. 给出列表清单。 How to make function which will data from list represent like 'moreline' string' like that every data will be shown in its new line, and in front of it are so many '*' as many as depth of data is. 如何使列表中的数据表示像'moreline'字符串'这样的函数,就像每个数据都会在新行中显示一样,而在它前面的数据就像数据深度那么多'*'。

Example : we have list [2, 4, [[3, 8], 1]] and now function has to make and return string, which function 'print' prints it out like this: 示例:我们有列表[2, 4, [[3, 8], 1]] ,现在函数必须生成并返回字符串,函数'print'将其打印出来,如下所示:

* 2
* 4
*** 3
*** 8
** 1

I have made for now just this and its not working 我现在已经做了这个,它没有用

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

if a replace return (s) with print(s) it report me an error ... but if i return s and than myself print that string it works normally , but once again not how it should 如果用打印替换返回它会报告错误...但如果我返回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

Where is the problem, I can't find it. 问题出在哪里,我找不到。 What should I replace, remove, etc.? 我该怎么替换,删除等?

You need to pass on count to recursive calls; 你需要将count传递给递归调用; local variables do not magically transfer to new function invocations: 局部变量不会神奇地转移到新的函数调用:

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)

I addressed various other issues with the code: 我用代码解决了其他各种问题:

  • Use descriptive function and argument names. 使用描述性函数和参数名称。 Function is not a great name. Function不是一个好名字。
  • Use a list to build up elements of a string, then use str.join() ; 使用列表构建字符串的元素,然后使用str.join() ; it is faster than building up strings by concatenation. 它比通过连接构建字符串更快。
  • Only increment the depth counter when recursing, not for every element in current level of the list. 仅在递归时递增深度计数器,而不是列表的当前级别中的每个元素。
  • Use isinstance() to test for specific types. 使用isinstance()来测试特定类型。
  • String formatting makes it a little easier to build strings together with constant elements, such as a space and a newline. 字符串格式化使得与常量元素(例如空格和换行符)一起构建字符串变得更容易一些。

Demo: 演示:

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

output: 输出:

*2
*4
***3
***8
**1

Often it's easier to express these things as a generator 通常,将这些东西表达为发电机更容易

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)

In Python3.3+ you can use yield from 在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)

Instead of catenating strings over and over, you can yield the depth/item as a tuple 您可以将深度/项目作为元组产生,而不是反复链接字符串

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM