Python:如何通过切片插入列表?

时间:2021-10-27 21:38:05

I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list and insert something into it to make it bigger? Thanks

我被指示防止这种情况发生在Python程序中,但坦率地说我不知道​​这是怎么回事。有人可以举例说明如何切割列表并在其中插入一些内容以使其更大?谢谢

2 个解决方案

#1


56  

>>> a = [1,2,3]
>>> a[:0] = [4]
>>> a
[4, 1, 2, 3]

a[:0] is the "slice of list a beginning before any elements and ending before index 0", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original list with those elements. You could also do the same anywhere else in the list by specifying a zero-width slice (or a non-zero width slice, if you want to also replace existing elements):

a [:0]是“在任何元素之前开始并在索引0之前结束的列表的切片”,其最初是空切片(因为在索引0之前原始列表中没有元素)。如果将其设置为非空列表,则会使用这些元素展开原始列表。您还可以通过指定零宽度切片(或非零宽度切片,如果您还要替换现有元素)在列表中的任何其他位置执行相同操作:

>>> a[1:1] = [6,7]
>>> a
[4, 6, 7, 1, 2, 3]

#2


0  

To prevent this from happening you can subclass the builtin list and then over-ride these methods for details refer here

为了防止这种情况发生,您可以继承内置列表,然后覆盖这些方法以获取详细信息,请参阅此处

#1


56  

>>> a = [1,2,3]
>>> a[:0] = [4]
>>> a
[4, 1, 2, 3]

a[:0] is the "slice of list a beginning before any elements and ending before index 0", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original list with those elements. You could also do the same anywhere else in the list by specifying a zero-width slice (or a non-zero width slice, if you want to also replace existing elements):

a [:0]是“在任何元素之前开始并在索引0之前结束的列表的切片”,其最初是空切片(因为在索引0之前原始列表中没有元素)。如果将其设置为非空列表,则会使用这些元素展开原始列表。您还可以通过指定零宽度切片(或非零宽度切片,如果您还要替换现有元素)在列表中的任何其他位置执行相同操作:

>>> a[1:1] = [6,7]
>>> a
[4, 6, 7, 1, 2, 3]

#2


0  

To prevent this from happening you can subclass the builtin list and then over-ride these methods for details refer here

为了防止这种情况发生,您可以继承内置列表,然后覆盖这些方法以获取详细信息,请参阅此处