Python 以 None 作为参数的列表切片

Python List Slicing with None as argument

通过反复试验,我发现

my_list = range(10)
my_list[:None] == my_list[:]

我将其用于 Django 查询集,因此我可以定义大小或全部使用:

some_queryset[:length if length else None]

# @IanAuld
some_queryset[:length or None]


# @Bakuriu
# length works for all numbers and None if you want all elements
# does not work with False of any other False values
some_queryset[:length]

应该是安全的。在Python中,something[<sliceexpr>]等同于something[slice(...)]slice类型的文档明确指出stop和step的参数默认为None

是的,使用 None 没问题,因为它的行为由 documentation:

指定

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

对切片参数之一使用 None 等同于省略它。

使用 None 或使用 [:] 之类的空切片没有区别,但是当您想在列表理解中使用它或在列表理解中使用它时,使用 None 很有用切片条件,例如:

>>> [my_list[:length if length%2==0 else None] for length in [1,2,3]]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

来自 CPython 来源 about slice function 中的评论:

Return a new slice object with the given values. The start, stop, and step parameters are used as the values of the slice object attributes of the same names. Any of the values may be NULL, in which case the None will be used for the corresponding attribute. Return NULL if the new object could not be allocated.

你的方式很好,但我会 更喜欢 :

some_queryset[:length] if length else some_queryset

some_queryset[:length] if length else some_queryset[:]

在不太了解切片如何处理这些特殊情况的情况下也可以阅读。

正如@kasravnd 的回答所描述的,使用 None 与在切片运算符中不指定任何内容相同(即它意味着 all),但它是有用的功能以防万一你想有条件地指定一个索引或 all.

然而,None还有另一种用法,但它仅适用于 Numpy 和 Pytorch:您可以在切片运算符中使用 None 来为数组添加额外的维度。

import numpy as np

abc=np.array([1,2,3])
print(abc[:,None])

这会打印:

array([[1],
       [2],
       [3]])