python - 如何获取嵌套列表中特定深度级别的所有元素?

标签 python list nested-lists

我正在寻找一种方法来获取嵌套在用户定义的列表深度级别的所有元素,例如:

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]

关于python - 如何获取嵌套列表中特定深度级别的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66946328/

相关文章:

python - 如何将两个用户定义的参数传递给 scrapy 蜘蛛

python - 有人可以解释方法属性上的 Python hasattr/delattr 吗?

python - 使用 rdflib 和 python 测试 dbpedia 页面的资源类型

python-3.x - 如何将两个嵌套列表附加到Python中的单个嵌套列表中

Python:从嵌套列表中删除单个元素

syntax-error - 如何在 NetLogo 中创建列表列表?

python - 安装 scikit : gcc-4. 2 未找到,使用 Clang 代替

Python:使数组的最后一项成为第一项

python - 将 .txt 文件转换为列表并能够逐行索引和打印列表

c# - 如何在同时删除项目的同时遍历列表?