python main() 未在 shell 中执行

python main() not executing in shell

我正在尝试 运行 我在 main 中的 flatten(li) 函数,但当我 运行 模块时它不是 运行ning。但是当我在 shell 中输入 "flatten(li)" 时,它正在工作。有任何想法吗?谢谢!

li = [0, 2, [[2, 3], 8, 100, None, [[None]]], -2]

def flatten(li):
     i = 0
     while i < len(li):
         "only execute if the element is a list"
         while isinstance(li[i], list):
             """taking the element at index i and sets it as the
                i'th part of the list. so if l[i] contains a list
                it is then unrolled or 'unlisted'"""
             li[i:i + 1] = li[i]
         i += 1

    for element in li:  
         if not element and not isinstance(element, int):
         li.remove(element)

    return li

def main():
    flatten(li)

if __name__ == '__main__':
    main()

它当然有效——你只是不打印任何东西,所以你看不到任何东西。尝试添加 print 调用:

if __name__ == '__main__':
    main()
    print(li)

你没有对输出做任何事情。我不确定你希望看到什么,但你想要的是这样的:

li = [0, 2, [[2, 3], 8, 100, None, [[None]]], -2]


def flatten(li):
    i = 0
    while i < len(li):
        while isinstance(li[i], list):
            li[i:i + 1] = li[i]
        i += 1

    for element in li:
        if not element and not isinstance(element, int):
            li.remove(element)

    return li


def main():
    flat = flatten(li)
    print(flat)


if __name__ == '__main__':
    main()