python - 迭代嵌套列表并选择某些元素并创建一个新列表

标签 python list recursion nested nested-lists

一个例子:

list = [[2, 1, 2, 3, 4],
       [0, 4, 5],
       [1, 8, 9]]

因此,嵌套列表中的第一个索引决定将哪些后续数字放入非嵌套列表中。

[2, 1, 2, 3, 4] -> 2: so 1 and 2 gets picked up
[0, 4, 5] -> 0: no number gets picked up
[1, 8, 9] -> 1; number 8 gets picked up

输出为:

[1, 2, 8]

这是我到目前为止所拥有的:

def nested_list(numbers):
    if isinstance(numbers[0], list):
        if numbers[0][0] > 0:
            nested_list(numbers[0][1:numbers[0][0] + 1])
    else:
        numbers = list(numbers[0])

    return numbers + nested_list(numbers[1:])

我尝试通过递归获取列表,但出现问题。我错过了什么或者即使没有递归也可以做到这一点?

最佳答案

您尝试在此处使用列表理解和元组解包。

[val for idx, *rem in lst for val in rem[:idx]] 
# [1, 2, 8]

NB This solution assumes you would always have a sub-list of size 1 or greater. We can filter out empty sub-lists using filter(None, lst)

关于python - 迭代嵌套列表并选择某些元素并创建一个新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69783807/

相关文章:

Python 参数解析 : args has no attribute func

python - 如何对字符串列表中的元素进行编号并返回一个新列表?

c++ - 不能在函数调用中使用 int 后递减

python - 通过字典中的不同值查找所有关键元素

haskell - 为什么我会收到有关空列表的错误?

c++ - 会不会在做递归内存的时候声明一个全局变量更高效更快?

python - 在 pandas.DataFrame 中保留最后 24 小时的日志

python - 无法在上下文菜单中执行按键并按 Enter 键 python selenium

python - sqlalchemy - 用 2 个条件连接子表

java - FreeMarker:左侧操作数:需要一个散列,但它已计算为一个数字(包装器:f.t.SimpleNumber)