这是我的列表(列表):
mylist = [ [1, "John", None, "Doe"], [2, "Jane", "group1", "Zee"], [3, "Lex", "group2", "Fee"]]
y = 2
for sublist in mylist:
if sublist[0] == y: # meaning the third list
if sublist[2] == None:
print(sublist[2]) # this should print nothing
else:
print(sublist[2]) #this should print something
最终结果是此代码不打印任何内容。
我正在尝试检查我的列表(列表)中是否有 None
值的情况。上面这个方法好像不行。
我不明白为什么它根本拒绝打印任何东西,但我认为嵌套的 if sublist[2] == None:
可能与它有关。
最佳答案
I am trying to do a check for situations where I have a None value in my list (of lists)
然后只需使用 in
检查每个子列表的成员资格:
for sublist in mylist:
if None in sublist:
# do your check
print("None in list: ", sublist)
打印:
None in list: [1, 'John', None, 'Doe']
如果您只想查看 None
是否存在,通常只需使用 any
:
any(None in sub for sub in mylist)
返回 True
因为 None
在 mylist[0]
关于python - 嵌套 if 语句在列表列表中不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354036/