检查嵌套列表中是否有 None
Check if None in nested list
如何在嵌套列表中查找 None。当我 运行 以下代码时,不会打印 Hello。我不知道如何在列表的列表中找到 None。你能帮我解决这个简单的问题吗?
myList = [[0,1,2],[5,None,300]]
if None in myList:
print("Hello")
这基本上是How to make a flat list out of list of lists?的特例;您需要将其展平才能执行测试。在这种情况下,最好的办法是使用itertools.chain
做扁平化,这样就可以使用in
短路测试(发现None
就停止) , 它后面的元素没有做任何工作):
from itertools import chain
myList = [[0,1,2],[5,None,300]]
if None in chain.from_iterable(myList):
print("Hello")
您可以使用任何:
myList = [[0,1,2],[5,None,300]]
if any(None in l for l in myList):
print("Hello")
或itertools.chain
:
from itertools import chain
if None in chain(*myList):
print("Hello")
请注意缩进:
for inner_list in myList:
for item in inner_list:
if item is None:
print('hello')
myList = [[0,1,2],[5,None,300]]
for x in myList:
if None in x:
print("Hello")
请注意,每找到一个 "None" 就打印一次。
如何在嵌套列表中查找 None。当我 运行 以下代码时,不会打印 Hello。我不知道如何在列表的列表中找到 None。你能帮我解决这个简单的问题吗?
myList = [[0,1,2],[5,None,300]]
if None in myList:
print("Hello")
这基本上是How to make a flat list out of list of lists?的特例;您需要将其展平才能执行测试。在这种情况下,最好的办法是使用itertools.chain
做扁平化,这样就可以使用in
短路测试(发现None
就停止) , 它后面的元素没有做任何工作):
from itertools import chain
myList = [[0,1,2],[5,None,300]]
if None in chain.from_iterable(myList):
print("Hello")
您可以使用任何:
myList = [[0,1,2],[5,None,300]]
if any(None in l for l in myList):
print("Hello")
或itertools.chain
:
from itertools import chain
if None in chain(*myList):
print("Hello")
请注意缩进:
for inner_list in myList:
for item in inner_list:
if item is None:
print('hello')
myList = [[0,1,2],[5,None,300]]
for x in myList:
if None in x:
print("Hello")
请注意,每找到一个 "None" 就打印一次。