Ich schrieb heute eine Funktion, dies zu tun:Warum geben my_list [None:] und my_list [: None] my_list zurück?
def foo(n=None):
my_list = generate_some_data()
return my_list if n is None else my_list[:n]
So fragte ich mich, was passieren würde, wenn n
None
war und ich habe my_list[:n]
. Also öffnete ich eine REPL und fand diese:
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]
Warum ist das? Was passiert unter den Abdeckungen, die Index None
spielt keine Rolle, und es verursacht nicht einmal einen Fehler?
Sie haben Ihre Antwort hier http://stackoverflow.com/questions/30622809/python-list-slicing-with-none-as-argument –