python复制列表无参数是什么意思_Python列表切片,无参数

本文探讨了在Django QuerySets中使用my_list[:None]等于my_list[:]的技巧,并解释了为什么在定义大小或取所有元素时,将长度设为None是一种合理做法。它适用于数字和None,但不适用于False或其他False值。作者还详述了None在切片参数中的行为准则和潜在问题。
摘要由CSDN通过智能技术生成

Via trial and error I found out that

my_list = range(10)

my_list[:None] == my_list[:]

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]

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:

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.

Using None for one of the slice parameters is the same as omitting it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值