在Python中使用冒号对列表进行切片时,使用大于列表长度的停止大小是否可以接受? [英] Is it acceptable to use a stop size larger than length of list when using colon to slice list in Python?

查看:71
本文介绍了在Python中使用冒号对列表进行切片时,使用大于列表长度的停止大小是否可以接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用my_list[:3]查找列表中的前3个元素,但我不能保证列表的长度至少为3.

I want to find the first 3 elements in list by using my_list[:3], but I cannot guarantee that the list will be at least length 3.

我只能找到具有给定列表和小句点的示例.因此,我想知道my_list[:3]是否可以接受,而不检查列表的长度.

I can only find examples with given list and small stop. So, I want to know whether my_list[:3] is acceptable without checking the length of list.

谢谢!

我已经尝试过了,效果很好.但是我想看看是否对文档有任何描述.

I have tried by myself and it works well. But I want to see whether any description of doc.

推荐答案

给出:

>>> li=[1,2,3]

实际上只有两种情况需要考虑.

There are really only two cases to consider.

1)如果切片超出了列表的末尾,它将传递已定义元素的重叠和空列表,且没有错误:

1) If a slice that extends beyond the end of the list, it will deliver the overlap of defined elements and an empty list beyond without error:

>>> li[2:]
[3]
>>> li[3:]
[]
>>> li[5555:]
[]
>>> li[1:55555]
[2, 3]
>>> li[555:55555]
[]

2)给定切片分配后,重叠的元素将被替换,其余的元素将被无误附加:

2) Given a slice assignment, the overlapping elements are replaced and the remaining elements are appended without error:

>>> li[1:5]=[12,13,14,15,16]
>>> li
[1, 12, 13, 14, 15, 16, 15]
>>> li[555:556]=[555,556]
>>> li
[1, 12, 13, 14, 15, 16, 15, 555, 556]

最后一种情况是,将切片分配给不存在的元素,因此将它们附加到现有元素上.

The last case there, the slice assignment was to non existing elements are were therefore just appended to the existing elements.

但是,如果右侧切片与左侧现有元素不匹配,则对于具有扩展切片的不存在元素(例如,如果您具有list_object[start:stop:step]),可能会有一个ValueError:

However, if the right hand slice does not match existing elements on the left hand, there can be a ValueError for non existing elements with an extended slice (i.e., if you have list_object[start:stop:step]):

>>> li
[1, 2, 3]
>>> li[1:7:2]=range(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 4 to extended slice of size 1

但是,如果它们存在,则可以进行扩展的切片分配:

But if they are existing, you can do an extended slice assignment:

>>> li=['X']*10
>>> li
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
>>> li[1:10:2]=range(5)
>>> li
['X', 0, 'X', 1, 'X', 2, 'X', 3, 'X', 4]

大多数时候-可以正常工作.如果要使用步骤进行分配,则元素必须存在.

Most of the time -- it works as expected. If you want to use a step for assignments the elements need to be existing.

这篇关于在Python中使用冒号对列表进行切片时,使用大于列表长度的停止大小是否可以接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆