Python – 在递归循环中查找列表中元素的“深度”

huangapple go评论62阅读模式
英文:

Python - Find the "depth" of an element in list in a recursive loop

问题

我想知道如何在Python中使用递归循环(而不是函数)来查找列表中元素的深度,但这段代码不起作用。我找到了一些使用函数的答案,但这不是关键。

在下面的列表中,类似'a'的深度为2,'d'的深度为3。

这是我的代码:

list1 = [['x', 'y'], ['z', 'p'], ['m', ['a', 'b', 'c', ['d', 'e']]]]

level = 0

def print_list(l):
    for e in l:
        global level
        if type(e) == list:
            print_list(e)
            level += 1
        else:
            print(str(e) + ",", str(level))

print_list(list1)

结果:

x, 0
y, 0
z, 1
p, 1
m, 2
a, 2
b, 2
c, 2
d, 2
e, 2

有人有想法吗?

英文:

I want to know the depth of an element in a list in Python using a recursive loop (not a function) but it doesn't work. I find some answers with functions but it's not the point here.

Something like 'a' is depth 2 and 'd' is depth 3 in the list below

Here is my code:

list1 = [['x','y'], ['z','p'], ['m',['a','b','c',['d','e']]]]

level = 0

def print_list(l):
    for e in l:
        global level
        if type(e) == list:
            print_list(e)
            level +=1
        else:
           print(str(e) + ",", str(level))
         
print_list(list1)

Result:

x, 0
y, 0
z, 1
p, 1
m, 2
a, 2
b, 2
c, 2
d, 2
e, 2

Someone has an idea?

答案1

得分: 2

使用生成器对这种任务非常方便。它允许您按需生成值或作为列表生成值,并使逻辑非常清晰。我将深度从-1开始,因为我希望第一个嵌套元素的深度为1(级别零将是像['a', ['b',...]]中的a这样的立即嵌套值):

list1 = [['x','y'], ['z','p'], ['m',['a','b','c',['d', 'e']]]]

def levels(l, depth = -1):
    if not isinstance(l, list):
        yield (l, depth)
    else:
        for sublist in l:
            yield from levels(sublist, depth + 1)
                
list(levels(list1))

结果:

[('x', 1),
 ('y', 1),
 ('z', 1),
 ('p', 1),
 ('m', 1),
 ('a', 2),
 ('b', 2),
 ('c', 2),
 ('d', 3),
 ('e', 3)]

将其转换为字典或使用各种 itertools 来操作它同样容易。

英文:

Using generators is really convenient for this kind of task. It allows you to produce values on demand or as a list and makes the logic very clear. I'm starting the depth at -1 because I want the first nested elements to be at depth 1 (level zero would be immediate nested values like a in ['a', ['b',...]]:

list1 = [['x','y'], ['z','p'], ['m',['a','b','c',['d', 'e']]]]

def levels(l, depth = -1):
    if not isinstance(l, list):
        yield (l, depth)
    else:
        for sublist in l:
            yield from levels(sublist, depth + 1)
            
list(levels(list1))

result:

[('x', 1),
 ('y', 1),
 ('z', 1),
 ('p', 1),
 ('m', 1),
 ('a', 2),
 ('b', 2),
 ('c', 2),
 ('d', 3),
 ('e', 3)]

It would be just as easy to make this a dictionary or use various itertools to manipulate it.

答案2

得分: 1

总的来说我建议尽量不要在递归中使用全局变量

list1 = [['x','y'], ['z','p'], ['m',['a','b','c',['d','e']]]]

def print_list(li, level):
    for e in li:
        if type(e) == list:
            level += 1
            print_list(e, level)
        else:
            print(str(e) + ",", str(level))

print_list(list1, 0)

输出:

x, 1
y, 1
z, 2
p, 2
m, 3
a, 4
b, 4
c, 4
d, 5
e, 5
英文:

In general I reccomend not using global variables, especially in recursion.

list1 = [['x','y'], ['z','p'], ['m',['a','b','c',['d','e']]]]

def print_list(li, level):
    for e in li:
        if type(e) == list:
            level += 1
            print_list(e, level)
        else:
           print(str(e) + ",", str(level))

print_list(list1, 0)

Output:

x, 1
y, 1
z, 2
p, 2
m, 3
a, 4
b, 4
c, 4
d, 5
e, 5

答案3

得分: 1

将这两行代码更改为:

level += 1
print_list(e)
level -= 1
英文:

Change these two lines:

print_list(e)
level +=1

to

level += 1
print_list(e)
level -= 1

答案4

得分: 0

生成器是一种好方法,这样你就不需要硬编码元素的使用或显示方式。

以下代码还使用了一个内部定义的函数,这样用户就不会意外传递额外的参数来破坏level

list1 = ['a',['b',['c',['d'],'e'],'f'],'g']

def enum_list(l):
    def _enum_list(l, level=1):
        for e in l:
            if isinstance(e, list):
                yield from _enum_list(e, level + 1)
            else:
                yield e, level
    yield from _enum_list(l)

for item, level in enum_list(list1):
    print(f'{item}, {level}')

输出结果:

a, 1
b, 2
c, 3
d, 4
e, 3
f, 2
g, 1
英文:

Generators are the way to go so you don't hard-code how the elements are used or displayed.

The following also uses an internally-defined function so the user can't accidentally pass an extra parameter that messes up level:

list1 = ['a',['b',['c',['d'],'e'],'f'],'g']

def enum_list(l):
    def _enum_list(l,level=1):
        for e in l:
            if isinstance(e,list):
                yield from _enum_list(e,level+1)
            else:
               yield e,level
    yield from _enum_list(l)

for item,level in enum_list(list1):
    print(f'{item}, {level}')

Output:

a, 1
b, 2
c, 3
d, 4
e, 3
f, 2
g, 1

huangapple
  • 本文由 发表于 2020年1月4日 01:51:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定