【问题标题】:extracting index from a nested list从嵌套列表中提取索引
【发布时间】:2021-08-20 06:24:35
【问题描述】:

我希望能够在嵌套列表中获取每个数字的索引,例如我有以下列表:

T = ['苹果', [10, 5, ['橙色']], 3]

我想提取这样的值:

数字列表:[10,5,3] 数字地址:[[1, 0], [1, 1], [2]]

例如,数字“3”是列表中的第三个值(索引 2),而数字“5”是第二个列表中的第二个值,因此它将是 [1,1]。

我已经编写了以下带有 for 循环的递归函数:

indices = []
List_numbers = []
Address_numbers = []

def Numbers(T):
    for index, elem in enumerate(T):
        if isinstance(elem, int):
            List_numbers.append(elem)
            Address_numbers.append(indices + [index])

        if isinstance(elem, list):
            indices.append(index)
            Fruits(elem)

    print('List of numbers: ' + str(List_numbers))
    print('Address of numbers: ' + str(Address_numbers))

此代码的问题是,当它到达最后一个值并需要退出列表时,它保持相同的索引,因此输出的地址是这样的:

List of numbers: [10, 5, 3]
Address of numbers: [[1, 0], [1, 1], [1, 2, 2]]

我已经尝试了一切来解决它,但老实说我不确定如何解决这个问题,有人可以帮忙吗?

【问题讨论】:

    标签: python list recursion


    【解决方案1】:

    使用recursive function 从嵌套列表中提取索引。
    使用recursion,您可以从嵌套列表中提取索引到任意深度:

    T = ['apple', [10, 5, ['orange']], 3]
    total_numbers = []
    indexes = []
    
    
    def find_index_of_numbers(lisst, level):
        for index, value in enumerate(lisst):
            if isinstance(value, int):
                total_numbers.append(value)
                indexes.append([level, index])
            elif isinstance(value, list):
                find_index_of_numbers(value, level + 1)
    
    
    find_index_of_numbers(T, 0)
    print("My list--->", T)
    print("Numbers--->", total_numbers)
    print("Indexes--->", indexes)
    

    输出

    My list---> ['apple', [10, 5, ['orange']], 3]
    Numbers---> [10, 5, 3]
    Indexes---> [[1, 0], [1, 1], [0, 2]]
    

    【讨论】:

    • 感谢您提供的解决方案,它对我有很大帮助,但有没有办法在不显示初始 0 的情况下做到这一点?所以它像 [2] 而不是 [0,2] ?
    猜你喜欢
    • 2023-04-01
    • 2017-07-19
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多