每日一题 【每日一题】将深度列表平面化 (不去重) -Python-20210911

Jack · 2021年09月11日 · 最后由 lework 回复于 2021年12月30日 · 68 次阅读
本帖已被设为精华帖!

深度列表:[1, [2], [[3], 4], 5] 平面化后:[1,2,3,4,5]

Jack 将本帖设为了精华贴 09月11日 18:24

参考代码:

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret
def deep_flatten(lst):
    result = []
    result.extend(
        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result
package main

type NextedIterator struct { // 扁平迭代器
    index int   // index是当前Next调用应该返回的第index个数
    nums  []int // 存放展平后的数字
}

func Constructor(nestedList []*NestedInteger) *NextedIterator {
    nums := []int{}
    for _, node := range nestedList { // 遍历nestedList
        flatten(node, &nums)
    }
    return &NextedIterator{index: 0, nums: nums} // 创建并返回扁平迭代器
}

func flatten(node *NestedInteger, nums *[]int) {
    if node.IsInteger() { // 如果是数字
        *nums = append(*nums, node.GetInteger()) // 将数字推入res
    } else { // 是nestedList
        for _, child := range node.GetList() { // 遍历nestedList,child是当前子元素
            flatten(child, nums)
        }
    }
}

func (this *NextedIterator) Next() int { // 一个个获取展平后的数组的元素
    val := this.nums[this.index] // 获取元素
    this.index++                 // 更新index
    return val
}

func (this *NextedIterator) HasNext() bool { // 是否还能获取到元素
    return this.index <= len(this.nums)-1 // 取决于index是否越了nums的界
}

func main()  {
    /*
    深度列表:[1, [2], [[3], 4], 5] 平面化后:[1,2,3,4,5]
    */
}
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册