[英]How to get all elements at a specific depth-level in a nested list?
我正在尋找一種方法來獲取嵌套在用戶定義的列表深度級別的所有元素,例如:
lst = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
# example 1
level = 1 # user defined level
output = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
# example 2
level = 2
output = [[1, 2], [3, 4], [5, 6], [7, 8]]
# example 3
level = 3
output = [1, 2, 3, 4, 5, 6, 7, 8]
您可以只使用遞歸算法,例如:
output = []
def extract(lists, d):
if d == 1:
return output.extend(lists)
for sub_list in lists:
extract(sub_list, d - 1)
對於 1 級:
extract(lst, 1)
print(output)
>>> [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
對於第 2 級:
extract(lst, 2)
print(output)
>>> [[1, 2], [3, 4], [5, 6], [7, 8]]
3級
extract(lst, 3)
print(output)
>>> [1, 2, 3, 4, 5, 6, 7, 8]
您可以使用chain.from_iterable
到 go 每次下降一級:
from itertools import chain
def get_at_level(lst, level):
for _ in range(level-1):
lst = chain.from_iterable(lst)
return list(lst)
例子:
>>> lst = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> get_at_level(lst, 1)
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> get_at_level(lst, 2)
[[1, 2], [3, 4], [5, 6], [7, 8]]
>>> get_at_level(lst, 3)
[1, 2, 3, 4, 5, 6, 7, 8]
請注意,function 僅返回原始列表的淺表副本。 因此,假設您以任何非最低級別調用 - 您將對原始子列表具有相同的引用。 這意味着修改返回的列表可能會* 更改原始列表,如果您不關心原始列表。 沒關系,如果您不想更改它,請在 function 的第一行中創建它的深層副本。
* 更改返回的第一級不會有問題,因為如前所述, list
返回淺拷貝。 但是,執行get_at_level(lst, 2)[0][0] = 0
之類的操作也會影響原件。
這不是一個非常干凈的問題解決方案,但它有效!
lst = [[[1,2],[3,4]],[[5,6],[7,8]]]
def function(lst, level):
if level == 1:
print(lst)
elif level == 2:
l2 = []
for x in lst:
for i in x:
l2.append(i)
print(l2)
elif level == 3:
l3 = []
for x in lst:
for i in x:
for a in i:
l3.append(a)
print(l3)
else:
print("Invalid depth level")
function(lst, 1) #level 1, 2 or 3
這里的問題是它不是動態的。
像下面這樣的遞歸func
可以工作。 這與馬科斯的回答基本相同。
func
接受一個列表作為它的第一個參數和深度作為第二個參數。
from functools import reduce
lst = [[[1,2],[3,4]],[[5,6],[7,8]]]
func = lambda x, d: x if d == 1 else func(reduce(lambda a,b: a+b, x), d-1)
func(lst, 3) # output [1,2,3,4,5,6,7,8]
您可以使用遞歸生成器 function:
def flatten(d, l=1):
for i in d:
yield from ([i] if l == 1 else flatten(i, l-1))
lst = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
print(list(flatten(lst, 3)))
print(list(flatten(lst, 2)))
print(list(flatten(lst, 1)))
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
[[1, 2], [3, 4], [5, 6], [7, 8]]
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.