V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
miniyao
V2EX  ›  Python

[] 和 [None] 有什么差别吗?

  •  
  •   miniyao · 2019-08-30 17:54:33 +08:00 · 2203 次点击
    这是一个创建于 1673 天前的主题,其中的信息可能已经有所发展或是发生改变。

    布尔值的比较是不相同的,在 for 循环的使用中也遇到过坑。foo 可能为空,用 for i in [] 是可以的,for i in [None] 把程序搞崩了。

    >>> [] == [None]
    False
    
    8 条回复    2019-09-11 12:09:58 +08:00
    swcsend
        1
    swcsend  
       2019-08-30 18:04:42 +08:00
    [None] 表示列表里面有一个 None
    [] 表示列表里面没有元素
    ClutchBear
        2
    ClutchBear  
       2019-08-30 18:15:22 +08:00
    for i in [None]
    如果有这种情况, 应该增加一个判断
    if i is None: continue
    GeruzoniAnsasu
        3
    GeruzoniAnsasu  
       2019-08-30 18:20:34 +08:00
    let l1 = []
    let l2 = [None]

    len(l1) == 0
    len(l2) == 1

    l1[0] ==> IndexError: list index out of range
    l2[0].__class__ ==> <class 'NoneType'>

    none2 = l2[0].__class__()
    none2 is None ==> True
    mixure
        4
    mixure  
       2019-08-30 18:37:10 +08:00
    代码上下文呢?
    Hstar
        5
    Hstar  
       2019-08-30 18:48:58 +08:00
    关键错误在于 for 循环内部不要 if i 这样判断,多一次 if i is None 筛选。
    CEBBCAT
        6
    CEBBCAT  
       2019-08-30 19:59:45 +08:00


    楼主该恶补基本功啦
    jmc891205
        7
    jmc891205  
       2019-08-30 20:07:40 +08:00
    空列表和包含一个 None 的列表肯定有区别啊
    否则,[], [None],[None, None], [None for i in range(10000)]都没有区别吗
    wangxiaoshan
        8
    wangxiaoshan  
       2019-09-11 12:09:58 +08:00
    空列表可以简单通过两个中括号[]表示,表示里面什么东西都没有。
    None 是 python 的内建值,含义是“这里什么也没有‘。比如如果要初始化一个长度 X 的序列,就需要让每个编码位置上都是空值,此时需要一个值代表空置,即里面没有任何元素,可以使用 None。
    >>> a=[None]*5
    >>>a
    [None,None,None,None,None]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2822 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:34 · PVG 22:34 · LAX 07:34 · JFK 10:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.