【发布时间】:2017-02-27 21:41:35
【问题描述】:
我正在尝试将嵌套列表扁平化为一个列表并删除所有无。但是,当有多个 None 时,总会有一个 None 剩余。有时我也有一个 None 作为 int 类型..(与第一个列表 li 中的第二个 None 一样)到底是什么?哈哈。请帮助我并提前感谢。
#test lists--li is the orignal one provided by Button
li = [0, 2, [[2, 3], 8, 100, None, [[None]]], -2]
li1 = [-100, -100, [[[None,None]]]]
li2 = [[[[[None,None,1,2,3]]]], 6, 0, 0, 0]
li3 = [None, [None], 56, 78, None]
li4 = [[[[[None,1,2,3]]]], 6, 0, 0, 0]
#solution is theta(n) or more specifically O(n)
#which is the best case solution since we must
#loop the entire list
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 li: for some reason the 2nd None at
#index 7 is an int, probably because there
#might've been an int at that index before manipulation?
#for li1: the 2nd None or element at index 3
#is of class 'NoneType' but the removal is not
#occuring..
for element in li:
if element is None:
li.remove(element)
#conclusion: there is always one None remaining if
#there is more than one None to begin with..
return li
def main():
flatten(li)
print(li)
flatten(li1)
print(li1)
flatten(li2)
print(li2)
flatten(li3)
print(li3)
flatten(li4)
print(li4)
if __name__ == '__main__':
main()
【问题讨论】:
-
None 作为 int 类型 - 这是什么意思?
-
在迭代列表时不要尝试从列表中删除项目。构建一个只包含您想要的项目的新列表要容易得多。
-
非常感谢 roganjosh!