布尔值的比较是不相同的,在 for 循环的使用中也遇到过坑。foo 可能为空,用 for i in [] 是可以的,for i in [None] 把程序搞崩了。
>>> [] == [None]
False
8 条回复 • 2019-09-11 12:09:58 +08:00
|
1
swcsend 2019 年 8 月 30 日
[None] 表示列表里面有一个 None
[] 表示列表里面没有元素 |
|
2
ClutchBear 2019 年 8 月 30 日
for i in [None]
如果有这种情况, 应该增加一个判断 if i is None: continue |
|
3
GeruzoniAnsasu 2019 年 8 月 30 日
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 |
|
4
mixure 2019 年 8 月 30 日
代码上下文呢?
|
|
5
Hstar 2019 年 8 月 30 日
关键错误在于 for 循环内部不要 if i 这样判断,多一次 if i is None 筛选。
|
|
6
CEBBCAT 2019 年 8 月 30 日
|
|
7
jmc891205 2019 年 8 月 30 日
空列表和包含一个 None 的列表肯定有区别啊
否则,[], [None],[None, None], [None for i in range(10000)]都没有区别吗 |
|
8
wangxiaoshan 2019 年 9 月 11 日
空列表可以简单通过两个中括号[]表示,表示里面什么东西都没有。
None 是 python 的内建值,含义是“这里什么也没有‘。比如如果要初始化一个长度 X 的序列,就需要让每个编码位置上都是空值,此时需要一个值代表空置,即里面没有任何元素,可以使用 None。 >>> a=[None]*5 >>>a [None,None,None,None,None] |
推荐学习书目
› 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
