python - 嵌套 if 语句在列表列表中不返回任何内容

标签 python python-3.x python-3.4

这是我的列表(列表):

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 因为 Nonemylist[0]

关于python - 嵌套 if 语句在列表列表中不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354036/

相关文章:

python - 如何在从 pandas 数据帧保存 SPSS 系统(sav)文件时将系统缺失值从 nan 重新编码为空白空间?

python - 如何让py2exe内置版权信息

python - 如何使用 PySimpleGUI 构建带有工作 Python 脚本的 GUI

python - 在函数末尾设置调试器断点而不返回

python - 将 os.path.join 与 os.path.getsize 一起使用,返回 FileNotFoundError

通过 SSH 运行后台服务的 Python 脚本

python - 嵌套单行循环

python - 字典创建说明

linux - 使用Python通过Serial读取不固定数量的字节

kivy - PyInstaller Kivy ClockApp 示例问题