【发布时间】:2016-10-04 04:40:59
【问题描述】:
我今天正在编写一个函数来做到这一点:
def foo(n=None):
my_list = generate_some_data()
return my_list if n is None else my_list[:n]
所以我想知道如果 n 是 None 而我是 my_list[:n] 会发生什么。于是我打开了一个 REPL 发现了这个:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> my_list = [1, 2, 3, 4, 5, 6]
>>> my_list
[1, 2, 3, 4, 5, 6]
>>> my_list[:4]
[1, 2, 3, 4]
>>> my_list[:None]
[1, 2, 3, 4, 5, 6]
>>> my_list[None:]
[1, 2, 3, 4, 5, 6]
>>> my_list[None:None]
[1, 2, 3, 4, 5, 6]
这是为什么?索引None 无关紧要甚至不会引发错误的幕后情况是什么?
【问题讨论】:
标签: python python-3.x