gpt4 book ai didi

python - 是列表[i :j] guaranteed to be an empty list if list[j] precedes list[i]?

转载 作者:IT老高 更新时间:2023-10-28 21:45:29 25 4
gpt4 key购买 nike

The Python tutorial解释了索引为负数时的切片行为,但我找不到描述结束索引在开始索引之前时的行为的文档。 (我也看过 Explain Python's slice notation ,也许我没有仔细阅读,但那里的答案似乎没有解决这一点。)

我观察到的行为是返回了一个空列表,这对我来说似乎是合理的。但是,在我看来,返回 i 之间的项目列表也是合理的。和 j以相反的顺序或简单地引发异常。

list[i:j]如果 list[j] 则保证为空列表在 list[i] 之前?

最佳答案

是的,如果 j <= i为真,对于标准 Python 类型,结果切片为空。要以相反的顺序获得结果,您需要添加负步幅:

list[i:j:-1]

因为显式优于隐式

这在 Common Sequence Operations 中有记录,脚注4:

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.

我的大胆强调。

自定义类型可以自由地以不同方式解释。

关于python - 是列表[i :j] guaranteed to be an empty list if list[j] precedes list[i]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28086896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com