我正在尝试在main中运行我的flatten(li)函数,但是当我运行模块时它没有运行。但当我输入" flatten(li)"在shell中它正在工作。有任何想法吗?谢谢!
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()
答案 0 :(得分:0)
它当然有效 - 你只是不打印任何东西,所以你什么也看不见。尝试添加print
来电:
if __name__ == '__main__':
main()
print(li)
答案 1 :(得分:0)
你没有对输出做任何事情。我不确定你期望看到什么,但这样的事情就是你想要的:
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()