Python - 找到“深度"递归循环中列表中的元素 [英] Python - Find the "depth" of an element in list in a recursive loop
问题描述
我想使用递归循环(不是函数)知道 Python 列表中元素的深度,但它不起作用.我找到了一些关于函数的答案,但这不是重点.
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.
在下面的列表中,像a"是深度 2 和d"是深度 3 之类的东西
Something like 'a' is depth 2 and 'd' is depth 3 in the list below
这是我的代码:
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
有人有想法吗?
推荐答案
对于此类任务,使用生成器非常方便.它允许您根据需要或作为列表生成值,并使逻辑非常清晰.我从 -1 开始深度,因为我希望第一个嵌套元素处于深度 1(零级将是直接嵌套值,例如 ['a', ['b] 中的
:a
',...]]
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))
结果:
[('x', 1),
('y', 1),
('z', 1),
('p', 1),
('m', 1),
('a', 2),
('b', 2),
('c', 2),
('d', 3),
('e', 3)]
将其制作成字典或使用各种itertools 操纵它.
It would be just as easy to make this a dictionary or use various itertools to manipulate it.
这篇关于Python - 找到“深度"递归循环中列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!