Python列表切片,无参数 [英] Python List Slicing with None as argument
本文介绍了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.
这篇关于Python列表切片,无参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文