Python列表切片,无参数
问题描述:
通过反复试验,我发现了
Via trial and error I found out that
my_list = range(10)
my_list[:None] == my_list[:]
我将其用于Django查询集,因此我可以定义大小或全部使用:
I use this for django query sets so I can define a size or take all:
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]
- 在切片时使用
None
是一种好习惯吗? - 在任何情况下,这种方法都会出现问题吗?
- Is this good practice to use
None
while slicing? - Can problems occur with this method in any case?
答
Yes, it is fine to use None
, as its behavior is specified by the documentation:
从i到j的s切片被定义为索引为k的项目序列,使得i≤k≤k. j.如果i或j大于len,请使用len.如果省略i或无,请使用0.如果省略j或无,请使用len .如果i大于或等于j,则切片为空.
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
与省略切片参数相同.
Using None
for one of the slice parameters is the same as omitting it.