python动态数组访问[:0][duplicate]

时间:2021-05-16 21:05:09

This question already has an answer here:

这个问题已经有了答案:

I try to access an array dynamically in a loop like array[n-i:-i] and it works fine as long as i != 0. In case i==0 I have array[n:0], which I would expect to output array from n to the end but it returns nothing (None i guess). How to archive the expected behaviour?

我尝试在数组[n-i:-i]这样的循环中动态访问一个数组,只要I != 0,它就可以正常工作。在i==0时,我有数组[n:0],我期望从n到end输出数组,但它没有返回任何值(我猜没有)。如何存档预期行为?

1 个解决方案

#1


11  

Use None to slice to the end; Python then'll use len(array) as the endpoint. Use or to fall back to None when -i is 0:

最后使用None切片;然后Python将使用len(数组)作为端点。当-i为0时使用或返回为None:

array[n-i:-i or None]

Numeric 0 is considered false in Python boolean contexts. The or operator short-circuits; it returns the first operand if it is a true value, otherwise it'll evaluate the second operand and return that.

在Python布尔上下文中,数字0被认为是假的。or操作符,可以终止;它返回第一个操作数,如果它是一个真值,那么它将计算第二个操作数并返回它。

#1


11  

Use None to slice to the end; Python then'll use len(array) as the endpoint. Use or to fall back to None when -i is 0:

最后使用None切片;然后Python将使用len(数组)作为端点。当-i为0时使用或返回为None:

array[n-i:-i or None]

Numeric 0 is considered false in Python boolean contexts. The or operator short-circuits; it returns the first operand if it is a true value, otherwise it'll evaluate the second operand and return that.

在Python布尔上下文中,数字0被认为是假的。or操作符,可以终止;它返回第一个操作数,如果它是一个真值,那么它将计算第二个操作数并返回它。